2017-04-21 116 views
1

我有繼承下面的代碼:如何在子類中定義getter和setter屬性

SubClass= function() { 
    ParentClass.call(this); 
} 
SubClass.prototype = Object.create(ParentClass.prototype); 
SubClass.prototype.constructor = SubClass; 

不過,我想定義在子類中的某些屬性,以及:

SubClass.prototype = { 

    get x() { 
     return this.newX; 
    }, 
    set x(val) { 
     this.newX = val; 
     alert("X has a value of " + this.newX); 
    } 
} 

的我遇到的問題是將兩者結合起來。換句話說,第一個代碼示例中,我說:

SubClass.prototype = Object.create(ParentClass.prototype); 

但隨後的第二個代碼示例中,我說:

SubClass.prototype = {... 

如何能夠做到兩者兼而有之?什麼語法可以讓我從父類繼承並使用相同的原型定義來定義屬性?

謝謝:)

回答

1

定義您的屬性通過傳遞一個屬性描述符Object.defineProperty

Object.defineProperty(SubClass.prototype, 'x', { 
    configurable: true, 
    get: function() { 
     return this.newX; 
    }, 
    set: function (val) { 
     this.newX = val; 
     alert("X has a value of " + this.newX); 
    }, 
}); 

也有可能包含屬性描述的對象傳遞給Object.create

function SubClass() { 
    ParentClass.call(this); 
} 

SubClass.prototype = Object.create(ParentClass.prototype, { 
    constructor: { 
     configurable: true, 
     writable: true, 
     value: SubClass, 
    }, 
    x: { 
     configurable: true, 
     get: function() { 
      return this.newX; 
     }, 
     set: function (val) { 
      this.newX = val; 
      alert("X has a value of " + this.newX); 
     }, 
    } 
}); 

如果您可以使用ES6課程,ES6課程更好:

class SubClass extends ParentClass { 
    get x() { 
     return this.newX; 
    } 

    set x(val) { 
     this.newX = val; 
     alert("X has a value of " + this.newX); 
    } 
} 

您也可以讓這種有用的功能:

function extend(target, source) { 
    Object.getOwnPropertyNames(source).forEach(function (name) { 
     var descriptor = Object.getOwnPropertyDescriptor(source, name); 
     Object.defineProperty(target, name, descriptor); 
    }); 
} 

,並使用它,像這樣:

extend(SubClass.prototype, { 
    get x() { 
     return this.newX; 
    }, 
    set x(val) { 
     this.newX = val; 
     alert("X has a value of " + this.newX); 
    }, 
}); 
+0

這是一個很大的幫助信息。非常感謝你!!! –

相關問題