javascript函数范围

ant*_*rna 8 javascript

谁可以在此代码中解释为什么结果为[20,20,10,10]:

var x = 10;
var foo = {
  x: 20,
  bar: function () {
    var x = 30;
    return this.x;
  }
};

console.log(
  foo.bar(),
  (foo.bar)(),
  (foo.bar = foo.bar)(),
  (foo.bar, foo.bar)()
);
Run Code Online (Sandbox Code Playgroud)

欢迎链接到规范

SWi*_*ilk 7

不能指出你的规格,但我强烈建议阅读道格拉斯克罗克福德的"Javascript:好的部分".本书将帮助您理解JavaScript的大多数奇怪但强大的功能.

截至你的问题:

  1. foo.bar(), 函数中的this关键字bar绑定到foo对象
  2. (foo.bar)()与上面相同,
  3. 在javascript中,您可以多次从右到左分配变量

    z = 3; x =(y = z); 的console.log(X); // 3

函数是其他任何变量.因此,您foo.bar要将函数分配给foo.bar,但括号会导致返回指定的函数,然后执行.

(foo.bar = foo.bar)(); 
//is the same as
var f = (foo.bar = foo.bar);
f(); 
//and this also the same as:
var f= foo.bar;
f();
Run Code Online (Sandbox Code Playgroud)

从括号返回的函数没有绑定到任何东西,因此this在浏览器的情况下将指向对象的全局window对象.

4 ..子句(foo.bar,foo.bar)()是相似的:

a = (3, 4); //last value is returned, first just parsed.
//a contains 4

var f = (foo.bar, foo.bar); 
//f contains body of foo.bar function, 
f() // is executed  in the context of `global` object, eg. `window`. 
Run Code Online (Sandbox Code Playgroud)

请阅读bindingJavaScript中的函数.