This may be a general javascript or jQuery question- I’m using backbone.js and I’d like to have a private method in one class that can be used by subclasses. Is this possible?
var fooView = Backbone.View.extend({
initialize: function () {
this._privateFunc();
},
_privateFunc: function () {
...
}
});
var subFooView = fooView.extend({
initialize: function () {
this.coolFunc();
this._privateFunc();
},
coolFunc: function () {
...
}
});
But then _privateFunc is not exposed to the outside world. I’m pretty new to encapsulation in javascript so forgive me if there’s an obvious answer. 😀
What you’re looking for is more accurately called protected rather than private accessibility. There’s no way to directly implement this in JavaScript.
Your best bet is probably just to expose
_privateFuncand use the convention that methods with underscores are only intended to be used by subclasses.You could also implement
__noSuchMethod__in the parent and then check that the method is being called by a subclass and execute the protected method. However, this is a Mozilla extension.