Javascript 类共享函数?

标签 javascript

假设我有两个类,一个称为“矩形”,一个称为“圆形”。两个类都有值 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/

相关文章:

javascript - 仅包含特定单词的过滤数组

javascript - 如何将粘性菜单包含在 float 侧边栏中?

Javascript函数在nodejs中返回未定义的值

javascript - 如何在 x 轴上设置固定金额,以便显示 future 的时间?

javascript - 范围选择器 - 仅在事件时更改条形颜色

javascript - node.js http(s) : get ip address of remote server

javascript - 使用 Typescript 声明字符串结构的最佳方法?

javascript - 插入 SQL 数据库时出现错误 502,没有主键

javascript - 在钛appcelerator中创建图像 slider

javascript - SweetAlert2 确认后禁用外部点击