example:
let x = 99;
function foo(p = x + 1) {
console.log(p);
}
foo() // 100
x = 100;
foo() // 101
However, if I change the parameters slightly to:
let x = 99;
function foo(x = x + 1) {
console.log(x);
}
foo() // NaN
x = 100;
foo() // NaN
Why is it displayed as NaN? What invisible changes occurred in the middle? If you know, can you tell me? Thanks
漂亮男人2017-05-19 10:46:17
let x = 99;
function foo(p = x + 1) {
console.log(p);
}
// 相当于
let x = 99;
function foo () {
let p;
p = x + 1;
console.log(p); // -> 100
}
The following code is equivalent to
let x = 99;
function foo(x = x + 1) {
console.log(x);
}
// 相当于
let x = 99;
function foo() {
let x; // 此时x = undefined;
x = undefined + 1;
console.log(x); // -> NaN
}
That is to say, the x in foo(x = x + 1) has nothing to do with the x outside. It is defined inside the function by you.