假设我有两个类,一个称为“矩形”,一个称为“圆形”。两个类都有值 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;
}
}
最佳答案
是的,有:
//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 中定义的任何函数。希望这会有所帮助。
关于Javascript 类共享函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643401/