2013-02-01 3 views
1

좋아하는 프로그래머 인 Douglas Crockford 중 한 사람, 특히 '방법'방법을 읽었습니다.Javascript로 묶어서, 왜이 코드에서 유용할까요?

자바 스크립트 :

Function.prototype.method = function (name, func) { 
    this.prototype[name] = func; 
    return this; 
}; 
function myfunc(value) { 
this.value=value; 
} 

myfunc.method('toString', function() { 
    return this.value; 
}); 

var testvar = new myfunc('myself').toString(); 
alert(testvar); 

은 내가 return this에 대한 혼란 스러워요.
여기에 return this의 의미는 무엇입니까?
이 메서드는 연쇄 (chaining)라고 불리는 것으로 작동하지만,이 '메서드'함수를 사용하여 체인을 어떻게 사용할 수 있습니까? 왜 유용합니까?

감사합니다.

답변

4

감사합니다.
변경 메커니즘은 확장하는 기능 (사용중인 객체)에 하나 이상의 프로토 타입을 추가하려는 경우에 유용합니다.
확장하여 예를 들어 아래를 참조

Function.prototype.method = function(name, func) 
{ 
    this.prototype[name] = func; 
    return this; 
}; 
function myfunc(value) 
{ 
    this.value = value; 
} 

myfunc 
    .method('toString',  function() {return this.value;}) 
    .method('toStringMore', function() {return this.value + ' more';}) 
    .method('bothFuncs', function() {return this.toString() + ' ' + this.toStringMore();}); 

var testvar = new myfunc('myself'); 

alert(testvar.toString()); 
alert(testvar.toStringMore()); 
alert(testvar.bothFuncs()); 

을 위로 return this이 결과는 '방법'함수의 두 번째 및 세 번째 호출이 실패했을 것입니다 다음 제외 된 경우.
체인 끝에 오른쪽까지 세미콜론이없는 것을 확인하십시오.

+0

오 바로 그래서 그게 전부는 유용하고 그게 어떻게 내 코드로 구현하는 이유에 도움이

희망. 매우 감사 –

관련 문제