Answer the question
In order to leave comments, you need to log in
How to organize inheritance in Javascript so that static methods are inherited?
My inheritance works like this:
var Parent = function(){
this.foo='foo';
};
Parent.prototype.method = function(){
console.log('i am not static');
};
Parent.staticMethod = function(){
console.log('i am static');
}
var Child = function(){
Parent.apply(this, arguments);
this.bar = 'bar';
};
Child.prototype = new Parent();
var kid = new Child();
kid.method();//все оукей
Child.staticMethod();//undefined is not a function
Child.staticMethod = Parent.staticMethod
Answer the question
In order to leave comments, you need to log in
extend?
function extend(target, source) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
return target;
}
And who needs a little perversion? Our functions are first-class citizens :)
var SuperClass = function (callback) {
callback.staticMethod = function () {
console.log('I\'m static');
};
return callback;
};
var Parent = SuperClass(function () {
this.foo = 'foo';
});
Parent.prototype = {
method: function () {
console.log('I\'m not static');
}
};
var Child = SuperClass(function () {
Parent.apply(this, arguments);
this.bar = 'bar';
});
Child.prototype = Object.create(Parent.prototype);
var kid = new Child();
console.log(kid.foo);
console.log(kid.bar);
kid.method();
Parent.staticMethod();
Child.staticMethod();
We send IE10 to hell - and all inheritance, both prototype and static methods, boils down to:
Child.__proto__ = Parent;
Child.prototype.__proto__ = Parent.prototype;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question