Skip to content

Instantly share code, notes, and snippets.

@ruanyf
Created March 4, 2015 03:18
Show Gist options
  • Save ruanyf/cae49b92b0bd43c4d57d to your computer and use it in GitHub Desktop.
Save ruanyf/cae49b92b0bd43c4d57d to your computer and use it in GitHub Desktop.
JavaScript作用域
function a(x,y){
y = function() { x = 2; };
return function(){
var x = 3;
y();
console.log(x);
}.apply(this, arguments);
}
a();
@JangoCheung
Copy link

3。进入a方法前,x,y被设置为undefined,a函数第一条语句执行,y被赋值为fun,fun中的x为a执行环境中的x。执行return方法,匿名函数中的x为该匿名函数执行环境的x,虽然又执行了y()但是y中的x为a函数执行环境的x,所以log为3。

@malcolmyu
Copy link

说白了就是 js 是静态作用域的。。不管怎么整最后输出的都是匿名函数里面 x 的值呗

@yibuyisheng
Copy link

函数的作用域嵌套关系在定义的时候就已经明确下来了,而不是在执行的时候才确定

@WayneCui
Copy link

WayneCui commented Mar 4, 2015

function foo() {
    console.log( a ); // 2
}

function bar() {
    var a = 3;
    foo();
}

var a = 2;

bar(); //2

@popomore
Copy link

popomore commented Mar 4, 2015

作用域的变量定义来自函数参数,var 定义,函数申明,否则继承自上层作用域。

以后 es6 增加 arrow function,block scope 和 default options 会更复杂

@zry656565
Copy link

https://gist.github.com/zry656565/a420989bfa8cb832addd 加了句代码,也许能帮助你理解。

@RCmerci
Copy link

RCmerci commented Mar 4, 2015

是3啊。不是很符合直觉吗?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment