Js混合对象“类”

来自《你不知道的javascript》的学习

《==============================================================》

类意味着复制。传统的类被实例化时,它的行为会被复制到实例中。类被继承时,行为也会被复制到子类中。

类的继承:

class Vehicle{

    engines = 1

    ignition(){

        output("Turning on my engine.");

    }

    drive(){

        ignition();

        output("Steering and moving forward!");

    }

}

class Car inherits Vehicle{

    wheels = 4

    drive(){

        inherited:drive();

        output("Rolling on all",wheels,"wheels!");

    }

}

class SpeedBoat inherits Vehicle{

        engines =   2;

         ignition(){

                output("Turning on my",engines,"engines.");

        }

        pilot(){

            inherited:drive()

            output("Speeding through the water with ease!")

        }

}

在pilot()中通过相对多态引用了(继承来的)Vehicle中的drive()。但是那个drive()方法直接通过名字(而不是相对引用)引用了ignition()方法。那么语言引擎会使用哪个ignition()呢,Vehicle的还是SpeedBoat的?实际上他会使用SpeedBoat的  ignition()。如果你直接实例化了Vehicle类然后直接调用它的drive(),那语言引擎就好使用Vehicle中的ignition()方法。总之,ignition()方法定义的多态性取决于你是在哪个类的实例中引用他。

猜你喜欢

转载自blog.csdn.net/gzkahjl/article/details/80994651
今日推荐