Could anyone please explain me..
Why baz
which is declared without a var
is not becoming a global variable
?
const foo = {
bar(baz) {
if (!baz)
baz = 1;
}
}
Because it's declared as a function parameter 1 :
const foo = {
bar(baz) {
// ^-------- here
if (!baz)
baz = 1;
}
}
( bar
is a function declared using ES2015 method definition syntax.)
If it weren't a parameter, for instance like this:
const foo = {
bar() {
// ^----------------- no baz
if (!baz)
baz = 1;
}
}
...then when foo.bar()
is called, if baz
weren't defined, it would be a ReferenceError
(because the Horror of Implicit Globals 2 only applies to assigning to undeclared symbols, not reading from them).
1 We frequently call these "arguments" loosely, but "argument" would technically be the actual value passed on a given call; see MDN and Wikipedia for the distinction.
2 That's a post on my anemic little blog.
Because it's a parameter.
Including it in the function declaration implicitly declares it for the given function scope.
Because you set it as a function's parameter. In order for a var to become 'global' (which can weaken the resiliency of programs and should be avoided) you should declare it outside of your function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.