在类之外声明方法

aur*_*enC 3 javascript methods

我知道我可以通过以下方式添加方法:

point.prototype.move = function () 
{
     this.x += 1;
}
Run Code Online (Sandbox Code Playgroud)

但是,有没有办法通过将一个在其外部声明的函数分配给它的一个属性来向类添加方法? 我很确定这不起作用,但它给出了我想要做的事情的想法:

function point(x, y)
{
     this.x = x;
     this.y = y;
     this.move = move();
}

function move()
{
     this.x += 1;
}
Run Code Online (Sandbox Code Playgroud)

Jua*_*des 6

您的示例不起作用的唯一原因是因为您正在调用move()并分配未定义的结果.

您应该move在分配时使用对该函数的引用.

function move()
{
     this.x += 1;
}

function point(x, y)
{
     this.x = x;
     this.y = y;
     this.move = move
}
Run Code Online (Sandbox Code Playgroud)

不同的方式来做到这一点

// 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; 
Run Code Online (Sandbox Code Playgroud)