我知道我可以通过以下方式添加一个方法:
point.prototype.move = function ()
{
this.x += 1;
}
但是,有没有办法通过将在类外部声明的函数分配给类的某个属性来向类添加方法? 我很确定这行不通,但它给出了我正在尝试做的事情的想法:
function point(x, y)
{
this.x = x;
this.y = y;
this.move = move();
}
function move()
{
this.x += 1;
}
最佳答案
您的示例不起作用的唯一原因是因为您正在调用 move()
并为其分配未定义的结果。
您应该在分配时只使用对 move
函数的引用。
function move()
{
this.x += 1;
}
function point(x, y)
{
this.x = x;
this.y = y;
this.move = move
}
不同的实现方式
// Attach the method to the prototype
// point.prototype.move = move;
// Attach the method to the instance itself
// var myPoint = new point(1,2); myPoint.move = move;
关于javascript - 在类外声明方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31663106/