aurelienC
aurelienC

Reputation: 1183

Declare method outside of class

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;
}

Upvotes: 3

Views: 2736

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92294

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; 

Upvotes: 6

jrath
jrath

Reputation: 990

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);

Upvotes: 4

Related Questions