问题
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