Why is using let resulting in undefined in a block of code?

坚强是说给别人听的谎言 提交于 2021-01-29 01:36:55

问题


When running code in a code block it results in 'undefined' then using the 'this' to reference a local variable in a block of code.

The strange thing is when removing the 'this' keyword in the same block, it prints fine.

let productId = 12;

if (true) {
    let productId = 10
    console.log(this.productId) // results in 'undefined'
    console.log(this) //results in '{}'
    console.log(productId) // results in '10'
}

Was under the impression that the 'this.productId' would refer directly to the productId in the true code block.


回答1:


'this' to reference a local variable in a block of code.

That never happens. It just looks that way if "local" and "global" happen to be the same.

Here you can see how it behaves when you use var in a global scope.

var foo = "global";

function myFunction () {
    var foo = "local";
    console.log(this.foo);
}

myFunction();

And here in strict mode:

"use strict";
var foo = "global";

function myFunction () {
    var foo = "local";
    console.log(this.foo);
}

myFunction();

The side-effect of using var in the global scope creating a window property of the same name is weird and confusing.

When let was created it wasn't designed to use the same weird and confusing behaviour.

this being window by default is also weird and confusing, and isn't the case in Strict mode.



来源:https://stackoverflow.com/questions/58802971/why-is-using-let-resulting-in-undefined-in-a-block-of-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!