有这样一小段程序,描述了两个类,每个类都有一对 getter&setter 属性:
Test1 是在 原型链 上定义的;
Test2 是用 ES6 中定义的;
// Test1
function Test1(val) {
alert("1");
this.value = val;
}
Test1.prototype = {
get value() {
alert("2");
return this._value;
},
set value(val) {
alert("3");
this._value = val;
}
};
var f1=new Test1("zj");
f1.value="sdf";
console.log(f1);
运行结果是:
弹出: 1 3 3 2;
输出:
[object Object] {
_value: "sdf",
value: "sdf"
}
// Test2
class Test2{
constructor(val){
alert("1");
this.value = val;
}
get value(){
alert("2");
return this._value;
}
set value(v){
alert("3");
this._value=v;
}
}
var f2=new Test2("zj");
f2.value="sdf";
console.log(f2);
运行结果是:
弹出: 1 3 3;
输出:
[object Object] {
_value: "sdf"
}
经过测试,在babel中转化后 test1 和 test2 是一样的的结果,题目中描述的结果是出现在jsbin上的,所以可能和他们的编译环境相关,两者不应该是有区别的,因为es6的类实现的过程相当于: