Sunday, 15 February 2015

Javascript Closures vs Object.createProperty -



Javascript Closures vs Object.createProperty -

my question follows : in or tutorials read closures first , foremost asset described them beingness able define private members . illustration , fabulous nettuts website : http://net.tutsplus.com/tutorials/javascript-ajax/digging-into-design-patterns-in-javascript/ . question follows - why take create objects closures , unnatural syntax , when can utilize object.definteproperty ? e.g

var o = {}; // creates new object // illustration of object property added defineproperty info property descriptor object.defineproperty(o, "a", {value : 37, writable : false, enumerable : true, configurable : true}); // 'a' property exists in o object , value 37

i must admit both ways much longer traditional oop languages , isn't sec way more natural ? why closures popular , other assets have , difference between creating object closure or way described?

it matter of syntax preference , browser compatibility. 1 big gotcha, if want browser compatible code, defineproperty method available in ie 9+ non-dom objects.

as far syntax goes, can see loose bit of phone call "visual encapsulation" when using defineproperty.

each way has own benefits, both lack simplicity of language supports privacy more directly.

note:

i assuming priavate mean setting writable property false.

reference

mdn: defineproperty

javascript closures

No comments:

Post a Comment