简体   繁体   中英

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?

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):

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM