admin管理员组

文章数量:1332322

i know i can add a method by doing:

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

But, is there a way to add a method to a class by assigning a function that is declared outside of it to one of its propertie? I am pretty sure this can't work but it gives an idea about what i'am trying to do:

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

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

i know i can add a method by doing:

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

But, is there a way to add a method to a class by assigning a function that is declared outside of it to one of its propertie? I am pretty sure this can't work but it gives an idea about what i'am trying to do:

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

function move()
{
     this.x += 1;
}
Share Improve this question edited Jul 27, 2015 at 21:51 Thomas Stringer 5,8623 gold badges27 silver badges42 bronze badges asked Jul 27, 2015 at 20:54 aurelienCaurelienC 1,1933 gold badges13 silver badges23 bronze badges 1
  • Well, did you test it? – Evan Davis Commented Jul 27, 2015 at 21:02
Add a ment  | 

2 Answers 2

Reset to default 6

The only reason your example doesn't work is because you are calling move() and assigning its result which is undefined.

You should just use a reference to the move function when assigning it.

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

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

Different ways to do it

// 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; 
function point(x, y, move)
{
     this.x = x;
     this.y = y;
     this.move = move;
}

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

var obj =  new point(2, 5, move);

本文标签: javascriptDeclare method outside of classStack Overflow