Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Closures vs Object.createProperty

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?

like image 807
Joel Blum Avatar asked Jan 17 '26 17:01

Joel Blum


1 Answers

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?.

like image 81
Bergi Avatar answered Jan 20 '26 21:01

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!