How to define common methods in node.js?

In node.js, I am struggling with classes / objects and the keyword 'this'. For instance:

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 as follows:

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

I have no problem 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 to create a method (e.g. geq ) in my object that has access to another method (e.g. leq ) in the same object when I need to access the first method, for example. sort function?

+4
source share
1 answer
 this.leq = leq ? leq : function(x,y) {return x<=y;}; 

Assign only the leq function to the current instance of Set

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

Will not work, because passing a function reference as instance.methodName does not bind this method to the specified instance

This can be solved using Function.bind .

+2
source

All Articles