写出JS中实现继承的几种方法

方法一:

// 定义父类

        function OneFather(name,age){

            this.name=name

            this.age=age

        }

        // 为父类原型中添加方法

        OneFather.prototype.say=function(){

            console.log("我是爸爸原型中的say方法(第一种继承方式)");

        }

        // 定义子类

        function OneSon(name,age,price){

            this.name=name

            this.age=age

            this.age=age

        }

        // 将子类的原型变换为父类的实例,这样就可以访问父类原型中的方法

        OneSon.prototype=new OneFather()

        // 修正子类原型中的constructor属性

        OneSon.prototype.constructor=OneSon
       // 实例化对象
        var one=new OneSon("jack",12,1000)
        // 调用say方法
        one.say()

方法二:


// 定义父类
        function TwoFather(name,age){
            this.name=name
            this.age=age
        }
        // 定义子类
        function TwoSon(name,age,price){
            // 改变this指向,相当于把TwoFather中的代码拿到这里执行
            TwoFather.call(this,name,age)
            this.price=price
        }

方法三


// 定义父类
        function ThreeFather(name,age){
            this.name=name
            this.age=age
        }
        // 为父类原型中添加方法
        ThreeFather.prototype.say=function(){
            console.log("我是爸爸原型中的say方法(第三种继承方式)")
        }
        // 定义子类
        function ThreeSon(name,age,price){
            //改变this指向,将父类代码加以复用
            ThreeFather.call(this,name,age)
            this.price=price
        }
        //  将子类的原型变换为父类的实例
        ThreeSon.prototype=new ThreeFather()
        // 修正子类原型中的constructor属性
        ThreeSon.prototype.constructor=ThreeSon
        // 实例化对象
        var three=new ThreeSon("jack",12,10000)
        three.say()

方法四:

// 定义父类
        function FourFather(name,age){
            this.name=name
            this.age=age
 }
        // 向父类原型中添加方法
        FourFather.prototype.say=function(){
            console.log("我是爸爸原型中的say方法(第四种继承方式)");
        }
        // 定义子类
        function FourSon(name,age,price){
            FourFather.call(this,name,age)
            this.price=price
        }
        FourSon.prototype=Object.create(FourFather.prototype)
        // 修正子类原型的constructor属性
        FourSon.prototype.constructor=FourSon
        // 实例化对象
        var four=new FourSon("jack",12,10000)
        four.say()

方法五

// 定义父类
        class FiveFather{
            // 在实例化时自动执行constructor方法            constructor(name,age){
                this.name=name
                this.age=age
            }
            say(){
                console.log("我是爸爸中的say方法(第五种继承方式)");
            }
        }
        class FiveSon extends FiveFather{
            constructor(name,age,price){
                // 调用父类的方法
                super(name,age)
                this.price=price
            }
        }
        var five=new FiveSon()
        five.say()

猜你喜欢

转载自blog.csdn.net/www340300/article/details/130323859