JavaScript语法(0,fn)(args) [英] JavaScript syntax (0, fn)(args)

查看:95
本文介绍了JavaScript语法(0,fn)(args)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需检查Google的JavaScript代码,我就找到了这样的语法:

Just checking Google's JavaScript code and I've found this syntax:

var myVar = function...;
(0, myVar)(args);

您知道这种语法的含义吗?
我找不到
(0,myVar)(args);

myVar(args); 。

Do you know the meaning of this syntax? I cannot find the difference between (0, myVar)(args); and myVar(args);.

举一个确切的例子,我们有

To give an exact example, we have

_.x3 = function (a, b) {
    return new _.q3(20 * b.x + a.B.B.x, 20 * b.y + a.B.B.y)
};

以后

this.ta = new _.s3((0, _.x3)(this.fa, this.B.B), 0);


推荐答案

我有同样的问题然后找到答案,如下:

I had the same question and then found the answer, as follows:

它真的适用于

(0, foo.fn)();

请记住,在JavaScript中,当 foo.fn(),然后在 fn 内,绑定到 foo 。如果您使用

Remember that in JavaScript, when foo.fn() is invoked, then inside of fn, the this is bound to foo. If you use

var g = foo.fn;
g();

然后当上面调用 g 时, 绑定到全局对象(窗口,在Web浏览器的上下文中)。

then when g is invoked above, the this is bound to the global object (window, in the context of a web browser).

那么你需要像上面那样定义 g 吗?你能做点什么吗?

So do you need to define g like above? Can you do something such as

(foo.fn)();

答案是否定的。 JavaScript会将它视为 foo.fn(); ,因为它只是 foo.fn 带有冗余()可以删除。

The answer is no. JavaScript will treat it the same as foo.fn(); as it is just foo.fn with the redundant () that can be removed.

但有一种方法可以解决它,它正是使用逗号运营商,Mozilla称之为

But there is one way to get around it, and it is exactly to use the comma operator, which Mozilla stated as


逗号运算符计算每个操作数(从左到右)并返回最后一个操作数的值

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand

所以使用

(0, foo.fn)();

(0,foo.fn)将被评估为对函数的引用,如上面的 g ,然后调用该函数。然后,未绑定到 foo ,但绑定到全局对象。

the (0, foo.fn) will get evaluated to a reference to the function, like g above, and then the function is invoked. And then, this is not bound to foo but is bound to the global object.

因此,以这种方式编写的代码是削减绑定​​。

So the code written this way, is to "cut the binding".

示例:

var foo = { 
              fullName: "Peter", 
              sayName:  function() { console.log("My name is", this.fullName); } 
          };

window.fullName = "Shiny";

foo.sayName();       // My name is Peter

(foo.sayName)();     // My name is Peter

(0, foo.sayName)();  // My name is Shiny

这篇关于JavaScript语法(0,fn)(args)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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