简体   繁体   English

返回后执行JavaScript代码

[英]JavaScript code executing after return

In the following example, JavaScript seems to be completely ignoring my return statement, and just carrying on executing code. 在下面的示例中,JavaScript似乎完全忽略了我的return语句,只是继续执行代码。

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

Surely the code should output 2 ? 当然代码输出2 If I remove the var keyword from var x = 3 , it outputs 2 as expected. 如果我从var x = 3删除var关键字,它会按预期输出2 Is there some strange compiler optimization at work here? 这里有一些奇怪的编译器优化吗?

No, the code shouldn't output 2 because variable declarations are hoisted so your code is equivalent to 不,代码不应该输出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

The line 这条线

x = 2;

only changes the internal x variable which shadows the outside one. 只更改影响外部x的内部x变量。

The scope of a non global variable is the entire function in which it is declared. 非全局变量的范围是声明它的整个函数。 From the start of this function to its end. 从这个功能的开始到结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM