Js scope explanation
Why the difference between the two is wrong in the first place? it feels like a scope, but I can"t tell why. Is there a specific
first
?
function e (v) {
console.log(w)
}
function a(z){
return function b(y) {
return function c(x) {
return function d(w) {
return e
}
}
}
}
a(1)(2)(3)(4)(5)
//
the second type
function a(z){
return function b(y) {
return function c(x) {
return function d(w) {
return function e (v) {
console.log(w)
}
}
}
}
}
a(1)(2)(3)(4)(5)
// 4
function e (v) {
console.log(w)
}
the first error is obvious, w is not defined.
has a hairy relationship with scope. The problem is that none of the values are passed
take a closer look at my following two ways of writing
function e (v) {
console.log(v)
}
function a(z){
return function b(y) {
return function c(x) {
return function d(w) {
return e(w)
}
}
}
}
a(1)(2)(3)(4) //4
=
function e (v) {
console.log(v)
}
function a(z){
return function b(y) {
return function c(x) {
return function d(w) {
return e
}
}
}
}
a(1)(2)(3)(4)(5) //5
the first, of course, is wrong.
function e (v) {
console.log(w)
}
The scope of
w is within the function e, and there is no definition
.
the second one will not report an error, you can take a look at the relevant knowledge of closures.
When a variable is referenced in
js, the current scope is not defined and the parent scope is looked for. You can simply understand that a {}
wraps a scope.
the piece of code that you can run successfully because the parent scope has a parameter w
, which refers directly to that variable and will not report an error. For the part where
cannot be run, there is window outside the function. Js searched all over the superior but could not find the definition of w
and reported an error
.