0

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!

1 Answers1

2

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;  }
}
  • Thanks a lot! Perhaps you know the reason to what I have a trouble? http://stackoverflow.com/questions/27986750/object-defineproperties-to-module-exports-in-nodejs –  Jan 16 '15 at 15:00