Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Do I understand it correctly?

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

2. Why this keyword in this.ns?

Since IIFE is invoked in global context, this keyword is linked with global, hence: document.ns (the namespace)

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

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

4. Since I passed window.ns as ns argument, why would I have to use this.ns and not just ns only?

like image 548
J. Lyde Avatar asked Oct 30 '22 17:10

J. Lyde


1 Answers

What argument is IIFE called with?

The window object does not have an .ns property on it at runtime. Therefore window.ns will evaluate to undefined, which in a || expression will coerce to false while {} will coerce to true. The || expression will therefore end up being false || true resulting in window.ns = {} being passed as the argument to the IIFE.

What happens inside the IIFE?

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

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

How to access window.ns and ns?

You can access window.ns from everywhere since it belongs to the global scope.

It is only the IIFE and functions within it that can access ns since it is declared in the lexical scope of the IIFE. However since the 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 lexical scope of the IIFE.

like image 176
rabbitco Avatar answered Nov 10 '22 00:11

rabbitco