Is it possible to inherit privileged methods in Javascript? In the below, Widget successfully inherits the D function, but not subscribe. Changing the second line in inherit to f.prototype = new base(); seems to work, but I know that’s bad for all sorts of reasons. Is there a clean way to do this, or do I have to make everything public? This answer seems to imply that I have to make the methods public (attach to prototype) but I’d like to ask directly.
function EventRaiser() {
var events = {};
this.subscribe = function(key, func) { /* elided */ };
}
EventRaiser.prototype.D = function() { alert("D"); };
function Widget() { }
function Inherit(sub, base) {
function f() { }
f.prototype = base.prototype;
sub.prototype = new f();
sub.prototype.constructor = sub;
}
Inherit(Widget, EventRaiser);
this.subscribe = function(key, func) { /* elided */ };here your adding a method to the current
thisContext.Inherit(Widget, EventRaiser)Here your saling the prototype Widget should consume the prototype EventRaiser.
The best you can do is to not mix
this.xwithprototype.yOr you can call
EventRaiser.call(this)insidefunction Widget() { }but that’s bad style.If your going to use an inheritance pattern I would recommend you use
Object.create&pd:Or if you insist
Widgetshould inherit fromEventRaiserThe reasons for recommending this pattern is a clear seperation of the prototype and the factory. This allows you to interact with the prototype without handling the factory. With the use of the
newkeyword you muddy those waters (as shown in your code) and you also tend to hackthisaround.The above code also doesn’t look elegant. This means that your realy aught to look for a different pattern. For example
EventEmitterfrom node.js has an explicit check for thethis._eventsobject which makes the factory code more elegant.