JS继承

        //原型继承
        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继承)