我想在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);
我想访问任何重写的方法,比如Rectangle,Circle,但是使用Shape对象,比如c#我们可以做什么:Shape shape = new Circle()shape.draw();它将调用子类的重写方法。我想在javascript中做同样的事情我该如何实现呢
答案 0 :(得分:0)
如果在代码中使用Shape
的任何子类(可以在运行时使用instanceof
运算符进行检查),则可以简单地调用该方法。 Js运行时会自动从原型链中调用正确的方法。因此,如果代码中有一个名为myshape
的对象,您可以:
if(myshape instanceof Shape){
// invoke draw method
myshape.draw();
}
答案 1 :(得分:0)
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);