ES6中的class继承

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' ]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • JS是一种基于对象的语言,要实现面向对象,写法跟传统的面向对象有很大的差异。ES6引入了Class语法糖,使得JS...
    开始懂了_317阅读 6,919评论 0 4
  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,183评论 3 11
  • 面向对象的语言都有一个类的概念,通过类可以创建多个具有相同方法和属性的对象,ES6之前并没有类的概念,在ES6中引...
    Erric_Zhang阅读 1,197评论 1 4
  • 就真滴很气 之前一直就是半斤八两的糊弄原型 今天的笔试题,GG 嗨呀 我要死磕了 网上有非常多的文章尝试去解释这个...
    灯不梨喵阅读 412评论 0 0
  • 今天看请回答1988,阿泽是个沉默寡言,和爸爸独自生活在一起异常懂事的孩子,比起胡同里其他要操碎了心的孩子们,阿泽...
    放牛班的小林子阅读 776评论 2 2

友情链接更多精彩内容