有這樣一小段程序,描述了兩個類,每個類都有一對 getter&setter 屬性:Test1 是在 原型鏈 上定義的;Test2 是用 ES6 中定義的;// Test1function 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"}// Test2class 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"}可以看到這兩種方式定義的getter&setter結果是不一樣的,請問是為什么呢?
在原型鏈和class中定義getter&setter有什么不同?
呼啦一陣風
2018-08-30 10:05:33