簡體   English   中英

有沒有更簡單的方法在JavaScript中為Object.defineProperty編寫

[英]Is there simpler way to write for Object.defineProperty in JavaScript

我有如下代碼,是否有更簡單的方法可以在JavaScript中編寫Object.defineProperty?

Object.defineProperty(window, "world",
{
  set: function(w)
  {
    return w();
  }
});

謝謝!

嘗試這個:

Object.defineProperties(window, {
    propertyOne:    {
        get:    function(){ },
        set:    function(i){ ... }
    },

    propertyTwo:    {
        get:    function(){ },
        set:    function(i){ ... }
    },

    propertyThree:  {
        get:    function(){ },
        set:    function(i){ ... }
    }
});

相當於:

Object.defineProperty(window, "propertyOne", {
    get:    function(){ },
    set:    function(i){ ... }
});
Object.defineProperty(window, "propertyTwo", {
    get:    function(){ },
    set:    function(i){ ... }
});
Object.defineProperty(window, "propertyThree", {
    get:    function(){ },
    set:    function(i){ ... }
});

在將函數分配給對象文字時(例如,設置JavaScript函數的原型時),也可以使用get / set關鍵字:

var Example =   function(element){
    this.element    =   element;
};

Example.prototype   =   {
    get colour(){ return this.element.style.backgroundColor; },
    set colour(i){ this.element.style.backgroundColor = i;  }
}

暫無
暫無

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

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