JavaScript中的间接函数调用

Art*_*Art 24 javascript ecma262

有类似的东西

f.call(...)
f.apply(...)
Run Code Online (Sandbox Code Playgroud)

但那就是这个

(1, alert)('Zomg what is this????!!!11')
Run Code Online (Sandbox Code Playgroud)

在这种情况下,"1"似乎没有多大意义,以下工作正常:

(null, alert)('Zomg what is this????!!!11')
(1, null, alert)('Zomg what is this????!!!11')
(undefined, alert)('Zomg what is this????!!!11')
Run Code Online (Sandbox Code Playgroud)

你能指出一下描述语法的ECMAScript的特定部分吗?

CMS*_*CMS 47

您只是使用逗号操作员.

此运算符仅从左到右计算其操作数,并从第二个返回值,例如:

(0, 1); // 1
('foo', 'bar'); // 'bar'
Run Code Online (Sandbox Code Playgroud)

在调用函数的上下文中,操作数的求值只会得到一个值,而不是一个引用,这会导致this调用函数内的值指向全局对象(或者它将undefined处于新的ECMAScript 5严格模式中) .

例如:

var foo = 'global.foo';

var obj = {
  foo: 'obj.foo',
  method: function () {
    return this.foo;
  }
};

obj.method();      // "obj.foo"
(1, obj.method)(); // "global.foo"
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,第一个调用,即直接调用,将this在内部的值method正确引用obj(返回"obj.foo"),第二个调用,由逗号运算符进行的评估将使this值指向全局对象(屈服)"global.foo").

这种模式近来越来越受欢迎,为了进行间接调用eval,这在ES5严格模式下很有用,例如,获取对全局对象的引用(想象一下你是在非浏览器环境中,window不是提供):

(function () {
  "use strict";
  var global = (function () { return this || (1,eval)("this"); })();
})();
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,内部匿名函数将在严格模式代码单元中执行,这将导致this值为undefined.

||运营商现在就第二个操作数的eval调用,这是一个间接调用,它将评估对全球词法和环境变量的代码.

但就个人而言,在这种情况下,在严格模式下,我更喜欢使用Function构造函数来获取全局对象:

(function () {
  "use strict";
  var global = Function('return this')();
})();
Run Code Online (Sandbox Code Playgroud)

使用Function构造函数创建的函数只有在使用严格使用指令时才是严格的,它们不像函数声明或函数表达式那样"继承"当前上下文的严格性.


Way*_*ett 8

它是逗号运算符,它评估它的两个操作数并返回第二个操作数的值.

因此,类似于(null, alert)评估alert函数,您可以使用括号立即调用.

它在ECMA-262(PDF)的第11.14节中描述.