如何在 node.js 中定义泛型方法?

jon*_*aug 5 javascript node.js this-keyword

在 node.js 中,我与类/对象和“this”关键字斗争。例如:

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)
Run Code Online (Sandbox Code Playgroud)

但是,如果我.sort像这样删除片段:

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

我没有任何问题:

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

但仍然:

 myset.arr.sort(myset.geq)

 TypeError: Object #<Object> has no method 'leq'
 at ...
Run Code Online (Sandbox Code Playgroud)

所以:当我需要访问第一个方法来例如函数时,如何geq在我的对象中创建一个方法(如),该方法leq可以访问同一对象中的另一个方法(如)sort

Aln*_*tak 2

this.leq = leq ? leq : function(x,y) {return x<=y;};
Run Code Online (Sandbox Code Playgroud)

只会将函数分配给leq当前实例Set

this.arr=arr.slice().sort(this.geq);
Run Code Online (Sandbox Code Playgroud)

不起作用,因为传递函数引用instance.methodName不会将该方法绑定到指定的实例

这可以通过使用 来解决Function.bind