Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在类外声明方法_Javascript_Methods - Fatal编程技术网

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;