超类具有“容器”属性。
当子类继承自超类时,“容器”属性在子类之间共享。
如何实现每个子类都有其父类及其所有属性的副本。
var a = function() {
};
a.prototype.ax = function() {
this.container = [];
}
var b = function() {
a.call(this);
}
b.constructor = b;
b.prototype = Object.create(a.prototype);
b.prototype.ax = function() {
a.prototype.ax();
this.container.push('b');
}
var c = function() {
a.call(this);
}
c.constructor = c;
c.prototype = Object.create(a.prototype);
c.prototype.ax = function() {
a.prototype.ax();
this.container.push('c');
}
var bi = new b();
var ci = new c();
bi.ax();
ci.ax();
// why bi container gets overriden?
console.log(bi.container);
您的问题在这里:
b.prototype.ax = function() {
a.prototype.ax();
this.container.push('b');
}
要调用超类函数,您需要像这样:
b.prototype.ax = function() {
a.prototype.ax.call( this );
this.container.push('b');
}
否则,您只是在调用ax
witha.prototype
作为上下文(的值this
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句