Outside class declaration method
I know I can add a method:
point.prototype.move = function ()
{
this.x += 1;
}
But, is there a way to add a method to a class by assigning a function declared outside of it to one of its properties? I'm sure it won't work, but this gives an idea of ββwhat I'm trying to do:
function point(x, y)
{
this.x = x;
this.y = y;
this.move = move();
}
function move()
{
this.x += 1;
}
+3
source to share
2 answers
The only reason your example doesn't work is because you are calling move()
and assigning its result to undefined.
You should just use the reference to the function move
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;
+5
source to share