12
// 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 实例。

除了必须将相同的吸气剂分配到新原型上之外,还有什么方法可以解决这个问题?

4

4 回答 4

12

一个更现代的解决方案是使用,Object.defineProperty因为它允许在不破坏它们的情况下处理 getter 和 setter。

唯一的问题是它需要一个描述符对象,因此不要手动创建一个,而是使用该Object.getOwnPropertyDescriptor函数为您获取它。

var BazValue = Object.getOwnPropertyDescriptor(Base.prototype,'value');

Object.defineProperty(Sub.prototype, 'value', BazValue);
于 2016-01-05T18:45:25.913 回答
11
Sub.prototype.__defineGetter__('value', Base.prototype.__lookupGetter__('value'));

试试看。

于 2011-05-18T04:00:09.803 回答
6

我认为如果你分配它会起作用

Sub.prototype = new Base()

问题是当您直接从 Base.prototype.value 分配构造函数时,它永远不会运行。在您拥有 Base 类的实例之前,该值将不存在(通过new

Function这是我扩展实现继承的典型方法:

Function.prototype.Extend = function(superClass) {
    this.prototype = new superClass();

    this.prototype.getSuperClass = function() {
        return superClass;
    };
    this.getSuperClass = this.prototype.getSuperClass;
    return this;
};

这将正确地将所有父类方法和属性分配给子“类”。

用法看起来像

var Sub = function() {}
Sub.Extend(Base)
于 2011-05-18T03:56:05.393 回答
2

除了Alex Mcp的回答之外,您还可以在使用以下方法扩展 Sub 之后向 Sub 添加新的 getter/setter:

Function.prototype.addGetter = function(val,fn){
    this.prototype.__defineGetter__(val,fn);
    return this;    
}
Function.prototype.addSetter = function(val,fn){
    this.prototype.__defineSetter__(val,fn);
    return this;    
}
//example;
Sub.Extend(Base);
Sub.addGetter('date',function(){return +new Date;});

并添加到tylermwashburns答案:您可以为此扩展 Function 原型:

Function.prototype.copyGetterFrom = function(val,fromConstructor){
    this.prototype.__defineGetter__(
         val
        ,fromConstructor.prototype.__lookupGetter__(val));
    return this;   
}
//usage example.:
Sub.copyGetterFrom('value',Base);
于 2011-05-18T04:43:29.673 回答