我曾经在js中使用匿名自执行功能:
((function(){
//do something
})();
但是我在某处发现了这个:
((function(){
//do something
}).call(this);
有什么不同?
我曾经在js中使用匿名自执行功能:
((function(){
//do something
})();
但是我在某处发现了这个:
((function(){
//do something
}).call(this);
有什么不同?
如果你通过this了,两种形式都是等价的。
但要查看差异,请查看下面的程序
var x = 5;
var o = { x: 10 };
function f()
{
alert(this.x);
}
f();
f.call(o);
f() -> 将警告 5。
f.call(o) -> 将提醒 10。
在第一个示例中,this它将是全局对象(window在浏览器领域),除非您处于 ES5 模式,否则它将是undefined.
在第二个示例中,this取决于this调用上下文中的 global内容——(undefined在 ES5 中)或对象实例。
function Foo() {
var that = this;
(function () {
console.log(this === window);
console.log(this === that);
console.log(typeof this === "undefined");
}());
(function () {
console.log(this === window);
console.log(this === that);
console.log(typeof this === "undefined");
}).call(this);
(function () {
"use strict";
console.log(this === window);
console.log(this === that);
console.log(typeof this === "undefined");
}());
}
new Foo();
[小提琴]
您还会发现.call()由于引擎必须做额外的工作来设置this上下文,调用在微观上会变慢。
一个在默认对象的上下文中调用它(window在浏览器中),另一个在任何上下文中调用它this。除非您在某个其他函数或with块中,this否则将是默认对象,因此该特定示例没有区别。
上下文确定this函数内部分配的值。