5

在 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)

但是,如果我像这样删除.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 ...

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

4

1 回答 1

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

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

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

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

这可以使用Function.bind.

于 2011-08-02T13:57:11.740 回答