JS继承

作者: smile丶ywx | 来源:发表于2019-06-08 17:35 被阅读0次
            //原型继承
            function SupType() {
                this.color = 'red';
            }
            SupType.prototype.getColor = function () {
                console.log(this.color)
                return this.color;
            }
            function SubType() {
                this.color = 'yellow'
            }
            SubType.prototype = new SupType();
            let subType = new SubType()
            subType.getColor()
    
            //构造继承,无法复用函数
            function SupType() {
                this.color = 'red';
            }
            SupType.prototype.getColor = function () {
                console.log(this.color)
                return this.color;
            }
            function SubType() {
                SupType.call(this)//可传参
            }
            let subType = new SubType()
            console.log(subType.color)
    
            //ES6
            class SupType {
                constructor() {
                    this.color = 'red'
                }
    
                getColor() {
                    console.log(this.color)
                    return this.color
                }
            }
    
            class SubType extends SupType {
                constructor(...args) {
                    super(...args)
                    this.color = 'yellow'
                }
            }
    
            let subType = new SubType()
            subType.getColor()
    

    相关文章

      网友评论

          本文标题:JS继承

          本文链接:https://www.haomeiwen.com/subject/nynixctx.html