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



在节点中.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)

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

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

我没有问题:

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

但仍然:

 myset.arr.sort(myset.geq)
 TypeError: Object #<Object> has no method 'leq'
 at ...

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

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

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

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

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

这可以使用Function.bind来解决。

最新更新