返回后执行JavaScript代码

dhu*_*lme 4 javascript

在下面的例子中,JavaScript似乎完全忽略了我的return语句,只是继续执行代码.

var x = 1;
(function() {
  x = 2;
  return;
  var x = 3;
})();
console.log(x); // Outputs 1 in both Chrome and FF
Run Code Online (Sandbox Code Playgroud)

当然代码应该输出2?如果我var从中删除关键字var x = 3,它会2按预期输出.这里有一些奇怪的编译器优化吗?

Den*_*ret 8

不,代码不应该输出2,因为变量声明被提升,所以你的代码相当于

var x = 1;
(function() {
  var x;
  x = 2; // changes the internal x variable
  return;
  x = 3; // does nothing because it's not reached
})();
console.log(x); // Outputs the outside x, which is still 1
Run Code Online (Sandbox Code Playgroud)

这条线

x = 2;
Run Code Online (Sandbox Code Playgroud)

只更改x阴影外部变量的内部变量.

非全局变量的范围是声明它的整个函数.从这个功能的开始到结束.