假设我有两个类,一个叫做Rectangle,另一个叫做Circle。这两个类都有值X和Y,有没有办法为两个类定义一次变量和函数?如果能够更好地解释,请阅读以下代码:
function Rectangle(msg, font){
this.msg = msg;
this.font = font;
}
function Circle(radius){
this.radius = radius;
}
Rectangle && Circle {
/* had no idea how to write the line above,
but basically for both the rectangle and the circle,
there is this code so I don't have to rewrite it for both.*/
this.position = function(x, y){
this.x = x;
this.y = y;
}
}
答案 0 :(得分:4)
是的,有:
//creating class shape
function Shape(x,y){
this.x = x;
this.y = y;
};
//set position function
Shape.prototype.position = function(x,y){
this.x = x;
this.y = y;
};
function Rectangle(msg,font,x,y){
//calling object Shape
Shape.call(this,x,y);
this.msg = msg;
this.font = font;
}
//inheriting object Shape
Rectangle.prototype=Object.create(Shape.prototype);
function Circle(radius,x,y){
//calling object Shape
Shape.call(this,x,y);
this.radius = radius;
}
//inheriting object Shape
Circle.prototype=Object.create(Shape.prototype);
现在可以从Rectangle或Circle对象中调用Shape中定义的任何函数。希望这会有所帮助。