Saturday, 15 May 2010

javascript - What benefits to var myObj = myObj || { } when myObj already exists? -



javascript - What benefits to var myObj = myObj || { } when myObj already exists? -

been reading javascript design patterns addy osmani, , in document simple assignment used 'prevent overwriting existing object/ namespace':

var myns = myns || function() {};

so understand assigns same object variable if exists, or creates empty 1 if (ideally) doesn't. suppose add together method object's prototype, already-existing, similarly-named object had similarly-named method outputted 'hi!'. next should happen, right?

myns.prototype.sayhello = function() { homecoming 'hello!' }; myns.sayhello(); // hello! ??

and original myns.sayhello() // hi! still overwritten, no? i.e. conditional variable assignment in case do, except add together 1 level of name-collision avoiding ? or wrong on this?

the purpose of form of assignment not avoid naming conflict, it's maintain existing object.

for example, if have 2 pieces of code adds properties or methods object, , don't know 1 of them runs first, or can't command that, can allow both utilize assignment that:

var myns = myns || {}; myns.dosomething = function(){ ... };

and somewhere else:

var myns = myns || {}; myns.dosomethingelse = function() { ... };

when both codes have run, have object both methods, , neither code relies on other exist or execute in specific order.

if want new object, should create new object.

if want avoid naming conflict, should maintain code in function scope variables local scope, , shadow variables same name global scope. approach used many libraries set little possible in global scope interfer other libraries.

javascript namespaces variable-assignment name-collision

No comments:

Post a Comment