美文网首页
ES6中的class继承

ES6中的class继承

作者: 江寻月 | 来源:发表于2017-11-24 14:30 被阅读0次

    ES6中的class继承

    class Father {
        constructor() {
            this.faterAge = 40
        }
        fatherRun() {
    
        }
    }  
    class Son extends Father {  
        constructor(name) {
            super(name)
            this.name = name
        }
            sonLaugh() {
    
        }
    }
    
    Son.prototype.sonRun = () => {
        console.log('gogogo');
    }
    
    
    let son1 = new Son('son1');
    
    let son2 = new Son('son2');
    

    Son(constructor function)的隐式原型proto指向Father(constructor function);
    Son 的显式原型prototype 指向Father的实例

    console.log(Son.__proto__ === Father)                           // true  
    console.log(Son.__proto__ === Father.prototype.constructor)     // true  
    console.log(Son === Son.prototype.constructor)                  // true
    console.log(Son.prototype instanceof Father)                    // true
    

    子类对象上有子类的属性和父类的属性

    console.log(son1.hasOwnProperty('name'));   // true
    console.log('name' in son1);            // true
    console.log(son1.hasOwnProperty('faterAge'));   // true
    console.log('faterAge' in son1);        // true
    console.log(Object.keys(son1))              // [ 'faterAge', 'name' ]
    

    子类的实例方法,实际上被添加到其父类的实例上(可以理解为子类的类对象--是对父类对象的扩充)。
    可以通过子类实例的proto,或者子类的prototype拿到该父类实例;

    console.log(son1.hasOwnProperty('sonRun'));                         // false
    console.log(son1.hasOwnProperty('sonLaugh'));                       // false
    console.log('sonRun' in son1);                              // true
    console.log('sonLaugh' in son1);                            // true
    
    
    console.log(son1.__proto__ instanceof Father);                      // true
    console.log(son1.__proto__.hasOwnProperty('sonRun'));               // true
    console.log(son1.__proto__.hasOwnProperty('sonLaugh'));             // true
    
    console.log(son1.__proto__.__proto__.hasOwnProperty('fatherRun'));  // true
    

    class声明时添加的实例方法是不可枚举的,而直接向Son.prototype添加的实例方法是可枚举的

    console.log(Object.keys(son1.__proto__))    // [ 'sonRun' ]
    

    相关文章

      网友评论

          本文标题:ES6中的class继承

          本文链接:https://www.haomeiwen.com/subject/fsffbxtx.html