나는 여러 개의 '모듈'을 사용하여 응용 프로그램을 만들고 있습니다. 각 모듈은 비슷한 기본 기능 세트를 필요로하므로 프로토 타입 상속을 통해 각 모듈이 상속하는 기본 모듈을 만들었습니다. 기본 모듈의 함수 이름 중 일부는 꽤 길기 때문에 이러한 함수가 자주 사용되므로 각 모듈 내에서 더 짧은 이름을 지정하려고합니다. 그러나이 값은 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))보다 정의되는 방식을 다소 변경하고 싶습니다.
감사합니다. 이 대답 일지 모르겠다. 필자의 코드와이 기사에서 설명한 부분적 구현이 IE8에서 작동하는지 평가할 필요가있다. –
@MarkBrown - MDN 기사에 설명 된 심이 트릭을 수행해야한다. 또는 [ES5 shim] (https://github.com/kriskowal/es5-shim/)을보십시오. 그러나 이것이 유일한 ES5 기능인 경우 과도 할 수 있습니다. –