码迷,mamicode.com
首页 > 编程语言 > 详细

谈谈javascript继承

时间:2017-09-28 01:07:50      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:class   this   super   color   const   cti   函数实现   func   实现继承   

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继承

标签:class   this   super   color   const   cti   函数实现   func   实现继承   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!