简体   繁体   English

有没有更简单的方法在JavaScript中为Object.defineProperty编写

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

I have a code as below, Is there simpler way to write for Object.defineProperty in JavaScript? 我有如下代码,是否有更简单的方法可以在JavaScript中编写Object.defineProperty?

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

Thanks! 谢谢!

Try this: 尝试这个:

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

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

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

Equivalent to: 相当于:

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){ ... }
});

It's also possible to use get/set keywords when assigning functions to an object literal (such as when setting a JavaScript function's prototype): 在将函数分配给对象文字时(例如,设置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