f.call和f()之间有什么区别

时间:2012-09-14 11:17:29

标签: javascript

我以前在js:

中使用匿名自执行功能
((function(){
  //do something
})();

但是我发现了这个地方:

((function(){
  //do something
}).call(this);

有什么区别?

3 个答案:

答案 0 :(得分:1)

如果您通过this,则两种表单都是等效的。

但要查看差异,请查看以下程序

var x = 5;
var o = { x: 10 };

function f()
{
    alert(this.x);
}

f();
f.call(o);
  

f() - >将提醒5。

     

f.call(o) - >会提醒10。

答案 1 :(得分:0)

在第一个示例中,this将是全局对象(浏览器中的window),除非您处于ES5模式,其中它将是undefined

在第二个示例中,this取决于this在调用上下文中的内容 - global(ES5中的undefined), 对象实例。

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();​

[Fiddle]

您还会发现.call()调用显微镜速度较慢,因为引擎必须执行额外工作才能设置this上下文。

答案 2 :(得分:0)

一个在默认对象(浏览器中为window)的上下文中调用它,另一个在this的上下文中调用它。除非您在某个其他函数或with块中,this将是默认对象,因此该特定示例没有区别。

上下文确定在函数内为this分配的值。