JS中的参数搜寻机制
1:
var color="blue";
function changecolor(color){
if(color=="blue"){
color="red";
}
else{color="green";}
console.log(color);//red
}
changecolor(color);
console.log(color);//blue
2:
var color = 'blue';
function changecolor () {
if (color === 'blue') {
color = 'red';
} else{
color = 'green';
}
}
changecolor();
console.log(color);//red
完全不同的执行结果 这是因为 参数的传递是值的传递
搜寻参数的机制是first local then global, 如果local没找到则到global中找。
- 如果函数parameter中没有定义color,函数中使用的color的值就是从global获取的“blue”;
- 如果函数parameter中定义了color,这就相当于新建了一个local变量,在图二例子中,该parameter is initialized, but hasn't been assigned a value, 此时color的值是undefined。

浙公网安备 33010602011771号