class Person {
constructor(name1) {
this.name1 = name1;
this._name= name1;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
get name2() {
//setter与getter命名不能与变量同名,否则会无限递归,此处用了_name2
return this._name2;
}
set name2(val) {
this._name2 = val;
}
}
let p1 =new Person('我是name1也是name');
console.log(p1.name);//打印_name默认为name1
p1.name = "我_name变了";
console.log(p1.name);//打印新的_name;
p1.name2 = "我是name2的初值,记住setter是用=来复制的不是方法调用";//name2没有初值需要先"setter"才能"getter"
console.log(p1.name2);
console