foo(x, y = function() { x = 2; }) {
var x = 3;
y();
console.warn(x);
}
foo();
Why foo() output 2 in react-native, but Chrome console output 3?
React-Native, by default, compiles code to ES2015 so the code actually runs should be similar to:
function foo(x) {
var y = arguments.length > 1 && arguments[1] || function() {
x = 2;
}
var x = 3;
y();
console.warn(x);
}
So when you run y() the x referenced is the x declared with var x = 3;. In Chrome console that actually supports default arguments, x references the variable in the arguments. See the code below:
function foo(x, y=function() { console.warn(x); x = 2; }) {
var x = 3;
y();
console.warn(x);
}
When you run foo(5) you'll see:
5
3
The reasion is @Lucas answered. ES2015 can not support default args. react native compiles code to ES2015.
foo(x, y=function() { console.warn(z); x = 2; z = 3}) {
var x = 3;
y();
console.warn(x);
}
So, foo(5) show "Can't find variable:z".
Chrome can support default args.
function foo(x, y=function() { console.warn(z); x = 2; z = 3 }) {
var x = 3;
y();
console.warn(x);
}
foo(5), you'll see:
3
3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With