是否有更简单的方法在JavaScript中编写Object.defineProperty

时间:2015-01-16 14:39:01

标签: javascript node.js

我的代码如下, 是否有更简单的方法在JavaScript中编写Object.defineProperty?

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

谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个:

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;  }
}