Reputation: 7878
My question is as follows : In most or all tutorials that I read about closures their first and foremost asset is described as them being able 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 as follows - Why would you choose to create objects with closures , with their somewhat unnatural syntax , when you can use Object.definteProperty ? e.g
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 must admit both ways are much longer than traditional OOP languages , but isn't the second way more natural ? Why then are closures so popular , what other assets do they have and what is the difference between creating an object with a closure or with the way I just described?
Upvotes: 3
Views: 535
Reputation:
It is a matter of syntax preference and browser compatibility. One big gotcha, is if you want browser compatible code, the defineProperty
method is only available in IE 9+ for non-dom objects.
As far as syntax goes, you can see that you loose a bit of what I call "visual encapsulation" when using defineProperty
.
Each way has its own benefits, but both lack the simplicity of a language which supports privacy more directly.
Note:
Reference
Upvotes: 0
Reputation: 664650
Object.defineProperty
still defines public properties, while closures allow privacy (you should not talk of private "members", it's just local variables).
Your example, using defineProperty
to define a enumerable, writable and configurable data property can (and should) be abbreviated by the default property assignment (which works in older browsers as well):
o.a = 37;
Not all objects need to be created with closures (and in your example I can't think of any application), but you might want to learn How do JavaScript closures work?.
Upvotes: 1