首页 > 编程语言 > 详细

谈谈javascript继承

时间:2017-09-28 00:55:23      阅读:226      评论:0      收藏:0      [点我收藏+]

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‘
            }
        }

 

谈谈javascript继承

原文:http://www.cnblogs.com/otfngo/p/7604649.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!