Yan*_*Yan 3 javascript react-native
foo(x, y = function() { x = 2; }) {
var x = 3;
y();
console.warn(x);
}
foo();
Run Code Online (Sandbox Code Playgroud)
为什么foo()在react-native中输出2,但是Chrome控制台输出3?
默认情况下,React-Native将代码编译为ES2015,因此实际运行的代码应类似于:
function foo(x) {
var y = arguments.length > 1 && arguments[1] || function() {
x = 2;
}
var x = 3;
y();
console.warn(x);
}
Run Code Online (Sandbox Code Playgroud)
所以,你在运行时y()的x引用是x有声明var x = 3;。在实际上支持默认参数的Chrome控制台中,请在参数中x引用变量。请参见下面的代码:
function foo(x, y=function() { console.warn(x); x = 2; }) {
var x = 3;
y();
console.warn(x);
}
Run Code Online (Sandbox Code Playgroud)
运行时,foo(5)您会看到:
5
3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |