原型-原型链-继承

继承的本质是原型链。原型链:

实例对象往上找相关联的原型对象,直到Object.prototype,这个过程形成了原型链。
实例可以通过原型链共享原型对象上的方法.

es5方式:Child4.prototype 的原型对象,引用了Parent4.prototype原型对象。故继承了构造函数Parent4的属性和方法。

        function Parent4() {
            this.name = "parent2"
            this.play = ['1', '2', '3', '4']
        }
        function Child4() {
        // ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this)) Parent4.call(
this) this.name = "child2" } Child4.prototype = Parent4.prototype; //只是引用 (都是对象),实现继承 var s1 = new Child4() var s2 = new Child4()

 

 

es6方式:

区别:

ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。

ES6的继承机制完全不同,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this

        class Persion {
            constructor(name) {
                this.name = name
            }
            eat() {
                console.log('会吃')
            }
        }
        class Child extends Persion {
            constructor(name,age) {
                this.age = age // 报错
                super(name) //表示父类的构造函数,创建父类this对象。子类没有自己的this对象,需继承父的。所以必须先有super,再使用this
            }
            run() {
                console.log('会跑么:',this.name)
            }
        }
        let xx = new Child('xixi')
        xx.hasOwnProperty('name') // true
        console.log(xx.name)  // xixi
        xx.eat()
        xx.run()
posted @ 2020-07-23 10:44  毛栗的demo  阅读(74)  评论(0)    收藏  举报