用窗口范围说明调用函数(0,function(){})() [英] Calling function with window scope explanation (0, function(){})()

查看:578
本文介绍了用窗口范围说明调用函数(0,function(){})()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么会这样:

I am curious as to why this works:

var c = {
    d: function myFunc() {
        console.log(this === window);   
    }
};
var a = {
    b: function() {
        console.log(this === a);
        (0,c.d)();
        c.d();
    }
};
a.b();

控制台输出:

True
True
False

所以它似乎是(0,cd)() cdcall(窗口)相同,但我似乎无法找到很多关于为什么或如何工作的人。任何人都可以解释一下吗?

So it seems to be that (0, c.d)() is the same as c.d.call(window), but I cannot seem to find much about why or how this works. Can anyone explain?

来自:关闭编译器问题

小提琴: http://jsfiddle.net/wPWb4/2/

推荐答案

如果你用逗号分隔多个表达式(),那么将评估所有表达式,但你最终会得到最后一个表达式的值:

If you write multiple expressions separated by a comma (,), then all expressions will be evaluated, but you will end up with the value of the last expression:

var x = (1,2,3);
console.log(x); // this will log "3"

现在(0,cd)是一个表达式,它将返回函数 cd ,但现在 c 不是此函数的了。这意味着将指向全局对象(窗口),或者在严格模式下保持未定义。你会得到同样的效果:

Now (0,c.d) is an expression that will return the function c.d, but now c is not the this of the function anymore. This means that this will point to the global object (window), or remain undefined in strict mode. You would get the same effect with any of these:

var f = function(x) { return x; };
f(c.d)();

或只是

var f = c.d;
f();

这篇关于用窗口范围说明调用函数(0,function(){})()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆