Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define generic methods in node.js?

In node.js I struggle with classes/objects and the 'this' keyword. E.g:

function Set(arr,leq) {
  this.leq = leq ? leq : function(x,y) {return x<=y;};
  this.arr=arr.slice().sort(this.geq);
}
Set.prototype.geq=function(x,y) { return this.leq(y,x);}

var myset = new Set([1,5,3,2,7,9]);


TypeError: Object #<Object> has no method 'leq'
at [object Context]:1:47
at Array.sort (native)
at new Set ([object Context]:3:22)
at [object Context]:1:13
at Interface.<anonymous> (repl.js:171:22)
at Interface.emit (events.js:64:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)

However, if I remove the .sort fragment like this:

function Set(arr,leq) {
  this.leq = leq ? leq : function(x,y) {return x<=y;};
  this.arr=arr.slice();
}

I have no problems with:

 var myset = new Set([1,5,3,2,7,9]);
 myset.geq(3,4)
 false

but still:

 myset.arr.sort(myset.geq)

 TypeError: Object #<Object> has no method 'leq'
 at ...

So: How do I create a method (like geq) in my object that has access to another method (like leq) in the same object when I need to access the first method to e.g. the sort function?

like image 908
jonhaug Avatar asked Nov 05 '22 17:11

jonhaug


1 Answers

this.leq = leq ? leq : function(x,y) {return x<=y;};

Will only assign the leq function to the current instance of Set

this.arr=arr.slice().sort(this.geq);

Won't work because passing a function reference as instance.methodName does not bind that method to the specified instance

This may be solved using Function.bind.

like image 77
Alnitak Avatar answered Nov 09 '22 04:11

Alnitak