简体   繁体   English

对这个 javascript 模式感到困惑

[英]Confused about this javascript pattern

Encounter following lines of code, but couldn't understand it.遇到下面几行代码,但是看不懂。

What is this (/ ... /)(this);这是什么 (/ ... /)(this); purpose in javascript? 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 ".此模式是“ 立即调用 Function 表达式”。 in short, it's just a function that is executed immediately.简而言之,它只是立即执行的 function。 the this on the end is a parameter to be sent to the inner function that will be accessed as exports最后的this是要发送到内部 function 的参数,将作为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.在您的示例中,我们可以假设无论this是什么,它都是一些 object 已向其添加了Move方法。

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有些人还称这种模式为“ 模块模式”,因为它创建了一个“封闭环境”,因此由于新的 function scope,它里面的东西是不可见的。换句话说,无论里面是什么,都可以看到外面,但外部只能看到内部允许它看到的

That pattern simply makes exports assigned to this at the time of execution.该模式只是在执行时将exports分配给this

Assuming the global scope and a browser, this will point to the window object.假设全局 scope 和浏览器, this将指向window object。

With those assumptions in mind, window.Move should contain the function assigned inside of that IIFE (Immediately Invoked Function Expression).考虑到这些假设, window.Move应该包含在该 IIFE 内部分配的 function(立即调用 Function 表达式)。

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.如果这个 function 在不同的上下文中被调用,而this不是window ,它将this方法分配给外部环境中的任何东西。

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有关此模块模式的更多信息,请查看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/有关一般 Javascript 模式的更多阅读,请查看http://addyosmani.com/resources/essentialjsdesignpatterns/book/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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