javascript - Extending namespaced module from within -


code:

;(function (ns, undefined) {   ns = {     foo1: "bar1"   }    this.ns = {     foo2: "bar2"   };    ns.foo3 = "bar3";    return ns;  })(window.ns = window.ns || {}); 

results:

calling ns result: object {foo2: "bar2"}

iife returns: object {foo: "bar1", foo3: "bar3"}

1. understand correctly?

  • ns new, private object inside iife returned
  • this.ns belongs window.ns , expands

2. why this keyword in this.ns?

since iife invoked in global context, this keyword linked global, hence: document.ns (the namespace)

3. how access this.ns properties inside iife?

e.g console.log(this.ns.foo2) - proper way?

4. since passed window.ns ns argument, why have use this.ns , not ns only?

what argument iife called with?

the window object not have .ns property on @ runtime. therefore window.ns evaluate undefined, in || expression coerce false while {} coerce true. || expression therefore end being false || true resulting in window.ns = {} being passed argument iife.

what happens inside iife?

the ns parameter passed window.ns = {} argument , ns = {foo1: 'bar1'} assigns new value ns , next ns.foo3 = 'bar3 adds property/value pair it.

the this defaults global object (window object in browser) when used in function declared in global scope. this.ns = {foo2: 'bar2'} therefore creates new property on window object name .ns , value {foo2: 'bar2'}.

how access window.ns , ns?

you can access window.ns everywhere since belongs global scope.

it iife , functions within can access ns since declared in lexical scope of iife. since iife returns ns, possible store return value in variable in global scope , thereby make ns accessible outside lexical scope of iife.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -