简体   繁体   English

为什么 javascript 不能在闭包内访问同名的外部变量?

[英]why javascript cannot access external variable with the same name inside the closure?

The following piece of javascript code:下面一段 javascript 代码:

function init(name) {
  function displayName() {
    var name = name || "default string";
    console.log(name); 
  }
  displayName();
}
init("parameter string"); //here is unexpected ouput: "default string"

Why does the above code not output " parameter string " as expected?为什么上面的代码不像预期的那样 output “ parameter string ”? Thanks in advance.提前致谢。

update: However, the following code works as expected:更新:但是,以下代码按预期工作:

function init(name) {
  var name = name||"Mozilla";
  console.log("init name:",name)
}
init("param string")//output: "init name: param string" as expected

what's the different between the two codes?这两个代码有什么不同?

Because On the left side, you declare a variable called name which will be undefined before get initialization, so the name value on the right side will be undefined, so name variable will initialize with "default string".因为在左侧,您声明了一个名为name的变量,该变量在 get 初始化之前将undefined ,因此右侧的name值将未定义,因此 name 变量将使用“默认字符串”进行初始化。

 function init(name) { function displayName() { var name = name || "default string"; console.log(name); } displayName(); } init("parameter string"); //here is unexpected ouput: "default string"

But if you remove var as @TJ Crowder suggest, you will re-assign the name parameter which already has value.但是,如果您按照@TJ Crowder 的建议删除var ,您将重新分配已经具有值的name参数。

 function init(name) { function displayName() { name = name || "default string"; console.log(name); } displayName(); } init("parameter string"); //here is unexpected ouput: "default string"

If you replace var with let it will give an error "Cannot access 'name' before initialization", which explain the point.如果将var替换为let会给出错误“初始化前无法访问 'name'”,这说明了这一点。

 function init(name) { function displayName() { let name = name || "default string"; console.log(name); } displayName(); } init("parameter string"); //here is unexpected ouput: "default string"

Because you declared same name variable inside closure function..因为您在闭包 function 中声明了name变量。

The below code should work下面的代码应该可以工作

function init(name) {
  function displayName() {
    var name1 = name || "default string";
    console.log(name1); 
  }
  displayName();
}
init("parameter string")

Otherwise you can directly check without declaring variable again否则你可以直接检查而无需再次声明变量

name = name || "default string";

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

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