本文介绍了javascript函数范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁可以在此代码中解释为什么结果为[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.

截至您的问题:


  1. foo.bar(),
    栏中的关键字功能是绑定到 foo 对象

  2. (foo.bar)()与上面相同,

  3. 在javascript中你可以多次从右到左分配变量

  1. foo.bar(),this keyword in bar function is bound to foo object
  2. (foo.bar)() is the same as above,
  3. 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函数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:04