简体   繁体   中英

Confused about this javascript pattern

Encounter following lines of code, but couldn't understand it.

What is this (/ ... /)(this); purpose in javascript? Does it have name for this pattern?

Code as below:

//Move.js
(function(exports){
  exports.Move = function(){

  };
})(this);

this pattern is an " Immediately Invoked Function Expresssion ". in short, it's just a function that is executed immediately. the this on the end is a parameter to be sent to the inner function that will be accessed as exports

(function(exports){

    //that was "this" outside, is now "exports" in here

}(this));

in your example, we can assume that whatever this was, it's some object that has been added a Move method to it.

some also call this pattern the " Module Pattern " in a sense that it creates a "contained environment" so that the stuff inside it is not visible to the due to a new function scope. in other words, whatever is inside sees the outside, but the outside can only see what the inside lets it see

That pattern simply makes exports assigned to this at the time of execution.

Assuming the global scope and a browser, this will point to the window object.

With those assumptions in mind, window.Move should contain the function assigned inside of that IIFE (Immediately Invoked Function Expression).

If this function were called in a different context where this is not window , it will assign that method to whatever this was in the outer environment.

This pattern is called "Module Pattern". There are various sub patterns and this one used Augmented Module pattern.

First, we import the module, then we add properties, then we export it. Here's an example, augmenting our MODULE from above:

For more read about this Module pattern check out http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

For more reading about general Javascript patterns check outhttp://addyosmani.com/resources/essentialjsdesignpatterns/book/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM