// Base class
var Base = function() {
this._value = 'base';
};
Base.prototype = {
constructor: Base,
// By function
getValue: function() {
return this._value;
},
// By getter
get value() {
return this._value;
}
};
// Sub class extends Base
var Sub = function() {
this._value = 'sub';
};
Sub.prototype = {
constructor: Sub
};
// Pass over methods
Sub.prototype.getValue = Base.prototype.getValue;
Sub.prototype.value = Base.prototype.value;
// ---
var mySub = new Sub();
alert(mySub.getValue()); // Returns 'sub'
alert(mySub.value); // Returns 'undefined'
乍一看,mySub.value 的返回值似乎与 mySub.getValue() 相同,但正如您所见,它返回的是 undefined。显然,getter 没有找到作为 Sub 实例 (mySub) 的父作用域,而是一个不存在的 Base 实例。
除了必须将相同的吸气剂分配到新原型上之外,还有什么方法可以解决这个问题?