Вопрос

Lets say you have a constructor ConstrA and want it to inherit from another constructor named SuperConstr and its prototype.

Can you simply do this:

SuperConstr = function() {};
SuperConstr.prototype.show = function (parm) {
    window.console.log(parm);
}
ConstrA = function () {
    this.value = 1;
}
ConstrA.prototype = SuperConstr.prototype; // <-----  Is this valid?
ConstrA.prototype.showAgain = function (parm) {
    window.console.log(parm * 2);
}
obj = new ConstrA();
obj.show(obj.value); // 1
obj.showAgain(obj.value); // 2

obj now appears to inherit from ConstrA and SuperConstr, but I'm not sure this is the right way to do this.

In other words, is the prototype of a constructor suppose to be equal (point to) the prototype of its constructor?

Это было полезно?

Решение

It's valid, but you no longer have two prototype objects, just the one.

So any methods you're trying to delegate won't actually be delegated, they will all exist on SuperConstr's prototype object.

A concern with this is that if you extend ConstrA's prototype, you're actually assigning to SuperContr's prototype, which is probably not what you want.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top