从内部扩展命名空间模块

J. *_*yde 5 javascript oop this module-pattern

码:

;(function (ns, undefined) {
  ns = {
    foo1: "bar1"
  }

  this.ns = {
    foo2: "bar2"
  };

  ns.foo3 = "bar3";

  return ns;

})(window.ns = window.ns || {});
Run Code Online (Sandbox Code Playgroud)

结果:

通话ns结果:Object {foo2: "bar2"}

IIFE回归: Object {foo: "bar1", foo3: "bar3"}

1.我理解正确吗?

  • ns 是IIFE中的一个新的私有对象,然后返回
  • this.ns属于window.ns并扩展它

2.为何选择this关键字this.ns

由于IIFE是在全局上下文中调用的this,因此关键字与global链接,因此:( document.ns命名空间)

3.如何正确访问this.nsIIFE内的物业?

例如console.log(this.ns.foo2)- 这是正确的方式吗?

自从我window.ns作为ns论点通过以来,为什么我必须使用this.ns而不仅仅是ns

rab*_*tco 2

IIFE 是用什么参数调用的?

\n\n

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 ||\xc2\xa0true resulting in window.ns = {} being passed as the argument to the IIFE.

\n\n

What happens inside the IIFE?

\n\n

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.

\n\n

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'}.

\n\n

How to access window.ns and ns?

\n\n

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

\n\n

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.

\n