2011-08-02 2 views
4

node.js에서 나는 클래스/객체와 'this'키워드로 고생하고 있습니다. 나는이 같은 .sort 조각 제거하면node.js에 일반 메소드를 정의하는 방법은 무엇입니까?

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) 

그러나, : : 예는 여전히

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 ... 

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

을 나는 어떠한 문제가 없다 어떻게해야합니까? 같은 메서드에서 (geq 같은) 다른 메서드 (예 : leq)에 대한 액세스 권한이있는 내 개체에서 첫 번째 메서드에 액세스해야 할 때 같은 개체를 예. sort 기능?

+0

이것은 순수한 JavaScript 질문이 아닙니까? retag 제안 - 포인트 2에 대한 – Paul

답변

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

은 현재 인스턴스에 leq 기능을 할당합니다 Set

this.arr=arr.slice().sort(this.geq); 
instance.methodName 같은 함수 참조를 전달하면 지정된 인스턴스에 그 방법을 결합하지 않기 때문에

가 작동하지 않습니다

이것은 Function.bind을 사용하여 해결할 수 있습니다.

+0

+1, 나는 혼란 스럽습니다. 1. 프로토 타입의 메소드는 인스턴스 자체에있는 것처럼 인스턴스에 대해 호출 할 수 있습니다. 메서드가 인스턴스에 있었던 경우 OP에 동일한 문제가 발생합니다. 아니면 내가 너 무슨 뜻인지 오해 한거야? – user113716

+0

@patrick 네, 맞아요. – Alnitak

+0

감사합니다, @Alnitak. 나는 'bind'방법을 알지 못했다. 관심을 가질만한 사람들을위한 해결책이있다. 첫 번째 코드 조각의 세 번째 줄을'this.arr = arr.slice(). sort (this.geq.bind (this)); – jonhaug

관련 문제