Javascript 在类外声明方法
我知道我可以通过以下操作添加方法:Javascript 在类外声明方法,javascript,methods,Javascript,Methods,我知道我可以通过以下操作添加方法: point.prototype.move = function () { this.x += 1; } 但是,有没有一种方法可以通过将在类之外声明的函数分配给它的一个属性来将方法添加到类中? 我很确定这是行不通的,但它给出了我正在尝试做的一个想法: function point(x, y) { this.x = x; this.y = y; this.move = move(); } function move()
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;
你测试过了吗?
// 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;