Closing Javascript and Object.createProperty

My question is this: Most or all of the tutorials I read about closing their first and main asset describe their ability to define private members. For example, from the fabulous nettuts website: http://net.tutsplus.com/tutorials/javascript-ajax/digging-into-design-patterns-in-javascript/ . My question is this: why did you decide to create objects with closures with their somewhat unnatural syntax, when you can use Object.definteProperty? eg,

var o = {}; // Creates a new object

 // Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", {value : 37,
                           writable : false,
                           enumerable : true,
                           configurable : true});
 // 'a' property exists in the o object and its value is 37

      

I have to admit that both ways are much longer than traditional OOP languages, but isn't the second way more natural? Why are locks so popular, what other assets do they have, and what is the difference between creating an object with a closure or as I just described?

+3


source to share


2 answers


It's a matter of syntax preference and browser compatibility. One big problem: if you want to use browser compatible code, the method defineProperty

is only available in IE 9+ for non-domain objects.

As far as syntax is concerned, you may notice that defineProperty

you lose some of what I call "visual encapsulation" when used .

Each has its own advantages, but both lack the simplicity of a language that directly supports privacy.

Note:



  • I assume priavate means that you are setting the writeable property to false.

Link

0


source


Object.defineProperty

still defines public properties, while closure allows privacy (you shouldn't talk about private "members", they're just local variables).

In your example, using defineProperty

to define an enumerable, writable, and custom data property can (and should) be abbreviated by assigning the default property (which also works in older browsers):



o.a = 37;

      

Not all objects need to be instantiated with closures (and in your example, I can't think of any application), but you can find out How JavaScript locks work? ...

+1


source







All Articles