问题描述
谁可以在此代码中解释为什么结果为[20,20,10,10]:
Who can explain why result are [20, 20, 10, 10] in this code:
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)()
);
欢迎链接到规范
推荐答案
无法指明您的规格,但我强烈建议您阅读。本书将帮助您理解JavaScript的大多数奇怪但强大的功能。
Can't point you at specification, but i can highly recommend reading Douglas Crockford's "Javascript: The good parts". This book will help you understand most of the weird but great features of JavaScript.
截至您的问题:
- foo.bar(),
栏中的
关键字foo
对象 - (foo.bar)()与上面相同,
-
在javascript中你可以多次从右到左分配变量
- foo.bar(),
this
keyword inbar
function is bound tofoo
object - (foo.bar)() is the same as above,
In javascript you can assign variables from right to left multiple times
z = 3;
x =(y = z);
console.log(x); // 3
z = 3;x = (y = z);console.log(x); //3
函数是其他任何变量。因此,您将函数 foo.bar
分配给 foo.bar
,但括号会导致返回已分配的函数,然后执行。
functions are variables as anything else. So you are assigning the function foo.bar
to foo.bar
, but the parenthesis causes the assigned function to be returned, and then executed.
(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();
从括号返回的函数没有绑定到任何东西,所以 this
将引用全局对象(如果是浏览器)到窗口
对象。
The function returned from parenthesis is not bound to anything, so this
will refer to global object, in case of browsers - to the window
object.
4 ..条款(foo.bar,foo.bar)()完全相同:
4.. The clause (foo.bar, foo.bar)() is just alike:
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`.
请阅读JavaScript中函数的绑定
。
Please read about binding
of functions in JavaScript.
这篇关于javascript函数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!