为什么将 var 传递给函数会使这个 var 在内部不可变?
why passing var to a function make this var immutable inside?
我是 js 的新手,我想了解这三种情况下 x 变量之间的区别,以及为什么这段代码中的第三种情况给我 x=10 仍然感到困惑
var x = 10;
function test(){
var x = 15;
}
test();
console.log(x)// return 10
///////////////////////////
var x = 10;
function test(){
x = 15;
}
test();
console.log(x)// return 15
////////////////////////////
var x = 10;
function test(x){
x = 15;
}
test();
console.log(x)// return 10
这是因为 x 是按值传递的(而不是引用)。请参阅此以获得更详细的解释:http://jasonjl.me/blog/2014/10/15/javascript/
var x = 10;
function test(){
var x = 15;
}
新 x
是在函数 scope
中创建的
var x = 10;
function test(){
x = 15;
}
x
属于外层范围
var x = 10;
function test(x){
x = 15;
}
Primitive parameters (such as a number) are passed to functions by
value; the value is passed to the function, but if the function
changes the value of the parameter, this change is not reflected
globally or in the calling function.
我是 js 的新手,我想了解这三种情况下 x 变量之间的区别,以及为什么这段代码中的第三种情况给我 x=10 仍然感到困惑
var x = 10;
function test(){
var x = 15;
}
test();
console.log(x)// return 10
///////////////////////////
var x = 10;
function test(){
x = 15;
}
test();
console.log(x)// return 15
////////////////////////////
var x = 10;
function test(x){
x = 15;
}
test();
console.log(x)// return 10
这是因为 x 是按值传递的(而不是引用)。请参阅此以获得更详细的解释:http://jasonjl.me/blog/2014/10/15/javascript/
var x = 10;
function test(){
var x = 15;
}
新 x
是在函数 scope
var x = 10;
function test(){
x = 15;
}
x
属于外层范围
var x = 10;
function test(x){
x = 15;
}
Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.