Extension module with name extension from the inside

Code:

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

Results:

Call ns result: Object {foo2: "bar2"}

IIFE returns: Object {foo: "bar1", foo3: "bar3"}

1. Do I understand this correctly?

  • ns is the new private object inside IIFE, which is then returned
  • this.ns belongs to window.ns and extends it

2. Why is this keyword in this.ns ?

Because IIFE is invoked in a global context, the this keyword is global, hence: document.ns (namespace)

3. How to properly access this.ns properties inside IIFE?

eg console.log(this.ns.foo2) is the correct way?

4. Since I passed window.ns as an argument to ns , why should I use only this.ns , not just ns ?

+5
source share
1 answer

What argument is called IIFE s?

The window object does not have the .ns property on it at run time. Therefore, window.ns will be evaluated to undefined , which in the expression || will be forced to false , and {} will force to true . Thus, the expression || will be false || true false || true , resulting in window.ns = {} passed as an IIFE argument.

What happens inside IIFE?

The ns parameter is passed with the argument window.ns = {} , and then ns = {foo1: 'bar1'} assigns a new value to ns , and then ns.foo3 = 'bar3 adds another property / value pair to it.

this defaults to the global object (the window object in the browser) when it is used in a function declared in the global scope. Therefore, this.ns = {foo2: 'bar2'} creates a new property in the window object with the name .ns and the value {foo2: 'bar2'} .

How to access window.ns and ns ?

You can access window.ns everywhere, as it belongs to the global scope.

Only IFEs and functions within it can access ns , as it is declared in the IIFE lexical domain. However, since IIFE returns ns , it is possible to store the return value in a variable in the global scope and thereby make ns accessible outside the IIFE lexical scope.

+2
source

Source: https://habr.com/ru/post/1259666/


All Articles