簡體   English   中英

使用getter / setter的Object.defineProperty()默認值

[英]Object.defineProperty() default value with getter/setter

我搞砸了一些“經典”繼承,並且遇到了一個問題。 我正在使用Object.defineProperty()向我的LivingThing “類”添加屬性。 我想要一個默認值,以及一個屬性獲取器/設置器。

http://jsfiddle.net/fmpeyton/329ntgcL/

我遇到以下錯誤:

Uncaught TypeError: Invalid property.  A property cannot both have accessors and be writable or have a value, #<Object>

為什么我會收到此錯誤?使用Object.defineProperty()獲得默認值和屬性的getter / setter的最佳方法是什么?

使用函數范圍的變量來支持已定義的屬性,並將該變量的初始值設置為默認值:

function LivingThing(){
    self = this;
    var isAlive = true;

    Object.defineProperty(self, 'isAlive', {
        get: function(){
            return isAlive;
        },
        set: function(newValue){
            isAlive = newValue;
        },
        configurable: true
    });

    self.kill = function(){
        self.isAlive = false;
    };
}

http://jsfiddle.net/329ntgcL/5/

writable是不必要的,因為您有二傳手。 這就是導致您出錯的原因。 您可以具有值/可寫(數據描述符)或獲取/設置(訪問器描述符)。

結果,當您調用var l = new LivingThingl.isAlive == true ;在調用l.kill()l.isAlive == false

您的getter / setter對提供了一個已計算的屬性,如果需要存儲,您可以(並且應該)將其與真實屬性一起備份:

self._isAlive = true;
Object.defineProperty(self, 'isAlive', {
    get: function(){
        return this._isAlive;
    },
    set: function(newValue){
        this._isAlive = newValue;
    },
    writable: true,
    configurable: true
});

大概在此放置一些邏輯,以證明setter / getter與常規屬性的合理性。 設置器用於包裝屬性訪問。

沒有setter和getter,可以通過將默認值分配給原型來定義默認值:

LivingThing.prototype.isAlive = true

var o = new LivingThing()

console.log(o.isAlive) // true

需要明確的是,在LivingThing實例上更改該屬性將為該實例創建一個屬性,而不更改其__proto__的值。

o.isAlive = false

console.log(new LivingThing().isAlive) // still true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM