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

查看:143
本文介绍了使用这种语法的原因是什么(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?

推荐答案

基本上,这种语法允许在窗口对象的上下文中调用 _.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()将会产生in Em() _ 的上下文中调用。在函数内部,这个关键字将引用 _ ,所以 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)()将方法调用与对象并在全局上下文中执行调用。在函数内部,这个关键字将引用窗口,所以 undefined ,因为窗口没有 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.

您可以在这个小提琴中测试两种语法之间的差异。

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

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

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