2012-05-08 2 views
2

나는 여러 개의 '모듈'을 사용하여 응용 프로그램을 만들고 있습니다. 각 모듈은 비슷한 기본 기능 세트를 필요로하므로 프로토 타입 상속을 통해 각 모듈이 상속하는 기본 모듈을 만들었습니다. 기본 모듈의 함수 이름 중 일부는 꽤 길기 때문에 이러한 함수가 자주 사용되므로 각 모듈 내에서 더 짧은 이름을 지정하려고합니다. 그러나이 값은 DOMWindow와 동일한 'this'값과 관련된 문제를 일으 킵니다.프로토 타입 상속과 'this'의 값

아래의 코드를 참조하십시오

var SAMPLEAPP = SAMPLEAPP || {}; 

//This is a base module that I want all other modules to inherit from 
SAMPLEAPP.Module = function(){ 

}; 

SAMPLEAPP.Module.prototype.someLongFunctionName = function(){ 
    console.log(this); 
}; 


//This is a module that inherits from the base module 
SAMPLEAPP.RouterModule= function(){ 
    var shortName = this.someLongFunctionName; 

    //This correctly logs 'SAMPLEAPP.RouterModule', but I would rather not type 
    //out this long function name each time I need to use the function 
    this.someLongFunctionName(); 

    //However, this code logs 'DOMWindow' when I would expect the value of 'this' 
    //to be the same as the direct call to this.someLongFunctionName 
    shortName(); 
}; 

SAMPLEAPP.RouterModule.prototype = new SAMPLEAPP.Module(); 


new SAMPLEAPP.RouterModule(); 

내 질문 : 전화 단축 이름은() SAMPLEAPP.RouterModule를 기록 있도록 어떻게 코드를 수정할 수 있습니까? 가능하다면, 모듈이 shortName에 대한 실제 호출 (즉, shortname.call (this))보다 정의되는 방식을 다소 변경하고 싶습니다.

답변

2

(하나가 작동이 차이가 인수가 함수에 전달하는 방법을 간단)이 될 수 있습니다 .

다른 방법으로,이 함수에 대한 컨텍스트를 결합하는 ES5 bind 방법을 사용할 수 있습니다 (이 경우를 문맥 this 될 것입니다) :

var shortName = this.someLongFunctionName.bind(this); 

그런 다음 shortName를 호출 할 수 있습니다 평소와 같이

shortName(); 

여기는 working example입니다.

바인드() 함수는 새로운 기능 (바운드 함수)를 생성하는 같은 기능 본체 (ECMAScript를 5 점에서 내부 통화 속성)와 함수와 : 그리고 여기 MDN 기사의 대부분의 관련 부분입니다 bind()의 첫 번째 인수 인이 값을 오버라이드 할 수없는 에 바인드 한 (바인드 된 함수의 타겟 함수)를 호출하고 있습니다.

+0

감사합니다. 이 대답 일지 모르겠다. 필자의 코드와이 기사에서 설명한 부분적 구현이 IE8에서 작동하는지 평가할 필요가있다. –

+0

@MarkBrown - MDN 기사에 설명 된 심이 트릭을 수행해야한다. 또는 [ES5 shim] (https://github.com/kriskowal/es5-shim/)을보십시오. 그러나 이것이 유일한 ES5 기능인 경우 과도 할 수 있습니다. –

0

shortName();으로 전화를 변경할 수 있습니다. shortName.call(this);.

이것은 자바 스크립트는 약간의 트릭입니다. 문맥에 기반합니다.

+0

감사합니다. 내 편집 내용을 참조하십시오. shortName()이라고하는 방식을 변경하지 않아도되는 솔루션을 선호합니다. –

1

호출/적용 기능을 사용하여 메서드 호출에 "this"컨텍스트를 전달할 수 있습니다. 귀하의 경우에는 그것은 하나가

shortName.apply(this); 

또는 다른 언급, 당신은 call 또는 apply 사용할 수

shortName.call(this); 
+0

감사합니다. 제 편집 내용을 보시고, shortName()이라고 부르는 방식을 변경하지 않아도되는 솔루션을 선호합니다. –

+0

긴 함수에 짧은 함수 이름을 제공하려는 경우 [module pattern] (http : //www.klauskomenda.com/code/javascript-programming-patterns/# 모듈) 또는 [공개 모듈 패턴] (http://www.klauskomenda.com/code/javascript-programming-patterns/#revealing) 또는 심지어 [공개 프로토 타입 패턴] (http://weblogs.asp.net/dwahlin/archive/2011/08/03/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern.aspx)? –