谈谈javascript继承

javascript实现继承大致有如下5种方式:

第1种,通过构造函数实现继承

        function Parent() {
            this.name = 'parent'
        }

        function Child() {
            Parent.call(this)
            this.type = 'child'
        }

第2种,通过原型链实现继承

        function Parent() {
            this.name = 'parent'
        }

        function Child() {
            this.type = 'child'
        }

        Child.prototype = new Parent()
        Child.prototype.constructor = Child

第3种,组合第1种和第2种方式

        function Parent() {
            this.name = 'parent'
        }

        function Child() {
            Parent.call(this)
            this.type = 'child'
        }

        Child.prototype = new Parent()
        Child.prototype.constructor = Child

第4种,是对第3种的优化,也是推荐的方式

        function Parent() {
            this.name = 'parent'
        }

        function Child() {
            Parent.call(this)
            this.type = 'child'
        }

        Child.prototype = Object.create(Parent.prototype)
        Child.prototype.constructor = Child

第5种,使用es6语法

        class Parent {
            constructor() {
                this.name = 'parent'
            }
        }

        class Child extends Parent {
            constructor() {
                super()
                this.type = 'child'
            }
        }

 

posted @ 2017-09-28 00:37  o天涯o  阅读(108)  评论(0)    收藏  举报