[英]How do I call a child method using the parent object in JavaScript?
我想在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,但是可以像在C#中那样使用Shape对象,我们可以做什么:Shape shape = new Circle()shape.draw(); 它会调用子类的重写方法。我想在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);
如果在代码中使用Shape
任何子类(可以在运行时使用instanceof
运算符进行检查),则可以简单地调用该方法。 Js运行时将自动从原型链中调用正确的方法。 因此,如果在代码中有一个名为myshape
的对象,则可以:
if(myshape instanceof Shape){
// invoke draw method
myshape.draw();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.