What's the reason for using such syntax (0, _.Em)();

偶尔善良 提交于 2019-12-17 10:55:11

问题


While investigating google plusone scripts, I've seen following syntax many times:

(0, _.Em)();

Assuming _.Em is a function the statement above would result in calling that function, that's pretty obvious. If, on the other hand, it would be undefined, wouldn't the result be the same as doing simply _.Em() ?

Can anyone shed a light on what's idea behind using such syntax?


回答1:


Basically, this syntax allows to call _.Em() in the context of the window object instead of _.

Assuming you have this code:

Foo = function() {
    this.foo = "foo";
};

Foo.prototype.Em = function() {
    alert(this.foo);
};

var _ = new Foo();

Issuing _.Em() will result in Em() being called in the context of _. Inside the function, the this keyword will refer to _, so foo will be printed.

Issuing (0, _.Em)() decouples the method call from the object and performs the call in the global context. Inside the function, the this keyword will refer to window, so undefined will be printed, since window does not have a foo property.

You can test the difference between the two syntaxes in this fiddle.



来源:https://stackoverflow.com/questions/9735424/whats-the-reason-for-using-such-syntax-0-em

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!