简体   繁体   English

如何在JavaScript中使用父对象调用子方法?

[英]How do I call a child method using the parent object in JavaScript?

I want to call child method using parent object in javascript how can I do it? 我想在javascript中使用父对象调用子方法吗?

var Shape = function () { }
    Shape.prototype.draw = function () {
        return "Generic shape called ";
    }

    var Circle = function () { }
    Circle.prototype = Object.create(Shape.prototype);
    Circle.prototype.draw = function () {
        return "I am from Circle";
    }

    var Rectangle = function () { }
    Rectangle.prototype = Object.create(Shape.prototype);
    Rectangle.prototype.draw = function () {
        return "I am from Rectangle";
    }

    var Triangle = function () { }
    Triangle.prototype = Object.create(Shape.prototype);

I want to access any overridden method like Rectangle, Circle any one but using Shape object like in c# what we can do: Shape shape=new Circle() shape.draw(); 我想访问任何覆盖的方法,例如Rectangle,Circle,但是可以像在C#中那样使用Shape对象,我们可以做什么:Shape shape = new Circle()shape.draw(); it will call overridden method of the child class.I want to do the same thing in javascript how can I achieve it 它会调用子类的重写方法。我想在javascript中做同样的事情如何实现

 var Shape = function () { } Shape.prototype.draw = function () { return "Generic shape called "; } Shape.prototype.val = 10; var Circle = function () { } Circle.prototype = Object.create(Shape.prototype); Circle.prototype.draw = function () { return "I am from Cirlce"; } var Rectangle = function () { } Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.draw = function () { return "I am from Rectangle"; } var Triangle = function () { } Triangle.prototype = Object.create(Shape.prototype); Triangle.prototype.draw = function () { return "I am from Triangle"; } //Using Up casting (access value of parent object) var newCircle = new Circle(); alert("newCircle: "+newCircle.draw()+" : "+newCircle.val); 

If you are using any subclass of Shape in your code ( you can check at runtime with instanceof operator) you can simple invoke the method. 如果在代码中使用Shape任何子类(可以在运行时使用instanceof运算符进行检查),则可以简单地调用该方法。 Js runtime would automatically call the right method from the prototype chain. Js运行时将自动从原型链中调用正确的方法。 So, if you have an object in code called myshape , you can: 因此,如果在代码中有一个名为myshape的对象,则可以:

if(myshape instanceof Shape){

    // invoke draw method
   myshape.draw();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM