我最近一直在研究一些JS库,这些库是由真正了解他们正在做什么的人编写的,我一直看到这种模式,而且我找不到有关它的信息.我阅读了.call()方法的文档,但它对我来说并没有多大意义.我希望通过实例获得其中一个经典的深入SO解释.
(function(undefined){
/*(insert entire library here)*/
}).call(this);
Run Code Online (Sandbox Code Playgroud)
这是关于什么的?为什么这是编写库的好方法?
请注意,有时undefined会省略,但我不知道将它放在那里有什么不同.我甚至不知道论据的来源,或者来电者是谁.
Hal*_*yon 28
让我们拆解这段代码.
首先,有一个匿名函数,可以立即调用.它与此类似:
(function () {/**/}).call();
(new Date()).getTime(); // timestamp since 1970 jan 1 in milliseconds
Run Code Online (Sandbox Code Playgroud)
我们不分配new Date()给变量,而是立即使用它.
现在为什么要使用.call而不仅仅是()?
.call是一种方法Functions都有.第一个参数是this将被绑定的内容,后续参数将作为参数传递给函数.所以:
(function () {
console.log(this.foo); // bar
}).call({ "foo": "bar" });
Run Code Online (Sandbox Code Playgroud)
这与undefined(见下文)一起使用.
.call是同为.apply一个微小的差别..apply只需要2个参数,其中第2个是参数数组.这将是类似的:
(function () {}).call(this, "foo", "bar");
(function () {}).apply(this, [ "foo", "bar" ]);
Run Code Online (Sandbox Code Playgroud)
apply的常见用法是与magic变量一起使用arguments.
(function () {
console.log(Array.prototype.slice.call(arguments, 1)); // [ "bar" ]
})([ "foo", "bar" ]);
Run Code Online (Sandbox Code Playgroud)
Array.prototype.slice.call(arguments, 1)可能看起来很可怕,但实际上它只是arguments.slice(1),但arguments不是Array这样,它没有slice功能.我们借用Array小号slice功能及使用方法.call来设置this到arguments.Array.prototype.slice(arguments, 1??)是不正确的.
现在为什么会出现this在.call(this)?this总是指向你所处的上下文.如果你在一个类的实例中,它将指向实例,如果你在全局范围内,它将指向那个.在浏览器环境中它也是window.
为什么undefined?因为我们.call(this)没有第二个参数,所以我们的匿名函数的所有参数都是undefined.我不确定为什么你需要在undefined那里创建一个显式变量.也许这是对某些浏览器或某些喜欢看到undefined定义的lint工具的支持.
感谢@TedHopp.undefined变化无常.
var undefined = "foo";
console.log(undefined); // undefined
(function (undefined) {
console.log(undefined); // "foo"
})("foo");
Run Code Online (Sandbox Code Playgroud)
您可以轻松拥有:
(function () {
/* code here */
}());
Run Code Online (Sandbox Code Playgroud)
这是完全有效的,并且工作原理相同.使用您发布的表单可能会有一些表现或利润.
| 归档时间: |
|
| 查看次数: |
8691 次 |
| 最近记录: |