8
8
88z2014-09-26 16:47:55
JavaScript
88z, 2014-09-26 16:47:55

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

As you noticed, Child.staticMethod === undefined.
I know what can be done:
Child.staticMethod = Parent.staticMethod
This solution does not eliminate me, because there are a lot of static methods, the class hierarchy will constantly grow and I don’t want to add a line of code for each class and method.
Please share your ideas for implementing inheritance in javascript, in which you can conveniently inherit static methods.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
deleted-tnorman, 2014-09-26
@deleted-tnorman

extend?
function extend(target, source) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
return target;
}

E
Evgeny Petrov, 2014-09-26
@Petroveg

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();

And by the way, because of this:
you get the foo property in the Parent prototype. Are you sure this is what you wanted?

K
Konstantin Kitmanov, 2014-09-27
@k12th

I like the way it's done in Backbone .

D
Denis Pushkarev, 2014-11-20
@rock

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 question

Ask a Question

731 491 924 answers to any question