鍍金池/ 問答/HTML/ ES6中class的get和set方法問題?

ES6中class的get和set方法問題?

Class 的取值函數(shù)(getter)和存值函數(shù)(setter),寫了一段測試代碼:

let str = 'nihao';
class MyClass {
    constructor() {
    }
    get prop() {
        return str ;
    }
    set prop(value) {
        str = value;
    }
}

class ParentClas extends MyClass{
    constructor(){
        super();
        this.prop='haha';
    }
}

let parentClass=new ParentClas();

console.log('parentClass.prop',parentClass.prop);
parentClass.prop="heihei";
console.log('parentClass.prop',parentClass.prop);
console.log("str",str);

運(yùn)行結(jié)果為:

clipboard.png

按照我的理解,parentClass對(duì)象有了自己的prop屬性,

parentClass.prop的訪問結(jié)果是haha,沒有問題

但是parentClass.prop="heihei";以后,修改的應(yīng)該是parentClass對(duì)象自身的prop屬性,parentClass.prop屬性為heihei,也沒有問題,但是為什么str變量竟然也是heihei了,按道理,不應(yīng)該訪問到MyClass原型鏈呀。

回答
編輯回答
孤巷

MyClass的原型鏈被parentClass繼承了,get、set方法你懂吧?監(jiān)聽屬性的取值、賦值動(dòng)作

2018年7月21日 21:20
編輯回答
舊螢火

parentClass.prop="heihei"這句話觸發(fā)了你的set啊,然后你的set當(dāng)中把str賦值成為heihei了啊

2018年7月12日 15:04
編輯回答
巴扎嘿

這個(gè)問題跟ES6的繼承機(jī)制有關(guān)系。

function Father() {

}

function Children(...args){
    Father.apply(this, args)
}
Children.prototype = new Father()

ES5的繼承,
實(shí)質(zhì)是先創(chuàng)造子類的實(shí)例對(duì)象this
然后再將父類的私有屬性添加到this上面
最后來改變原型鏈的指向
但也會(huì)有一些問題
假設(shè)父類構(gòu)造函數(shù)上存在計(jì)數(shù)
這也會(huì)導(dǎo)致計(jì)數(shù)不準(zhǔn)確的問題

ES6的繼承機(jī)制完全不同
實(shí)質(zhì)是先創(chuàng)造父類的實(shí)例對(duì)象this
所以必須先調(diào)用super方法
(即便子類沒有書寫constructor也會(huì)默認(rèn)添加)
然后再用子類的構(gòu)造函數(shù)修改this

2017年11月28日 12:29
編輯回答
嫑吢丕
parentClass.prop = 'hehe'
parentClass.hasOwnProperty('prop') // false
2017年7月22日 12:10