使用这种语法的原因是什么 (0, _.Em)(); [英] What's the reason for using such syntax (0, _.Em)();

查看:29
本文介绍了使用这种语法的原因是什么 (0, _.Em)();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在研究 google plusone 脚本时,我多次看到以下语法:

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

(0, _.Em)();

假设 _.Em 是一个函数,上面的语句会导致调用该函数,这很明显.另一方面,如果它是未定义的,结果会不会与简单地执行 _.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?

推荐答案

基本上,这个语法允许在 window 对象的上下文中调用 _.Em()而不是 _.

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

假设你有这个代码:

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

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

var _ = new Foo();

发出_.Em() 将导致Em()_ 的上下文中被调用.在函数内部,this 关键字将引用_,因此将打印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.

发出(0, _.Em)() 将方法调用与对象分离,并在全局上下文中执行调用.在函数内部,this 关键字将引用window,因此将打印undefined,因为window 不会有一个 foo 属性.

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.

您可以在this fiddle中测试两种语法之间的差异.

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

这篇关于使用这种语法的原因是什么 (0, _.Em)();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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