函数作用域的理解(1)
var x={name:"one"};
function test(x,y=function(){x.name = "two";console.log(x.name);}){//two
var x={name:"three"};
y();
console.log(x);//three
}
test(x);
console.log(x.name);//two
var x={name:"one"};
function test(x,y=function(){x.name = "two";console.log(x.name);}){//two
//var x={name:"three"};
y();
console.log(x.name);//two
}
test(x);
console.log(x.name);two
var x={name:"one"};
function test(x,y=function(){console.log(x.name);x.name = "two";}){//报错
//var x={name:"three"};
y();
console.log(x.name);
}
test();
console.log(x.name);
通过上面函数实验得知,test函数在初始化参数作用域时,参数作用域是拥有自己的独立作用域,它有一下表现:
1.如果没有传值,则x为undefined,尽管y函数定义了x,但是他不属于这个作用域,它属于这个作用域的子作用域;
var x={name:"one"};
function test(x,y=function(){var x = {name:"two"};}){
//var x={name:"three"};
y();
console.log(x.name);//报错
}
test();
console.log(x.name);
2.如果传入值,则参数等于(=)传入的值;y函数是单独作用域,不会影响test的作用域,如果y中没有声明,则会x指向传入对象,会影响外部x的值
var x={name:"one"};
function test(x,y=function(){var x = {name:"two"};}){
//var x={name:"three"};
y();
console.log(x.name);//one
}
test(x);
console.log(x.name);//one
var x={name:"one"};
function test(x,y=function(){x.name = "two"}){
//var x={name:"three"};
y();
console.log(x.name);//two
}
test(x);
console.log(x.name);//two
3.函数内部的作用域如果有声明,则取内部声明的参数,如果没有,则取参数声明的变量,但y函数属于独立的作用域,相当于并列的关系,它声明的变量不会影响test内部;
var x={name:"one"};
function test(x,y=function(){var x={name:"two"};}){
var x={name:"three"};
y();
console.log(x.name);//three
}
test(x);
console.log(x.name);//one
var x={name:"one"};
function test(x,y=function(){var x={name:"two"};}){
x.name="three";
y();
console.log(x.name);//three
}
test(x);
console.log(x.name);//three