이렇게 힘듭니다. 직접 메서드를 호출 할 때 이것은 문자열 변환에서 호출 할 때 "window"를 참조하는 동안 포함 된 객체를 참조합니다 (나는 완전히 틀릴 수 있습니다).자바 스크립트와이 오류. 기능 호출 방법에 따라
아무에게도 설명 할 수 없습니까?
무엇이 일어날 것은
/**
* converts a string to a function
*/
function stStringToFunction(string) {
var fnList = string.split(".");
var currentFn = window;
var nextFn;
while(currentFn !== undefined && (nextFn = fnList.shift())) {
currentFn = currentFn[nextFn];
}
return currentFn;
}
//An example library
UnderstandingThis.ui.Component1 = {
performTask1: function(options) {
var settings = {
opt1: true,
opt2: false
},
_this = this;
$.extend(settings, options);
_this._PrivateTask1(settings);
},
_PrivateTask1: function(settings) {
//Some sweet stuff here!
alert("Private task1: " + settings.from);
}
}
UnderstandingThis.ui.Component1.performTask1({from: "direct"});
stStringToFunction("UnderstandingThis.ui.Component1.performTask1")({from: "string-to-function"});
설명 내 부족 편집을 요구
(즉 직접 호출 _this
가 정의 된 방법으로 잘 작동을 의미) 첫 번째 경고 문 뒤에 자바 스크립트 오류 : 2/21/2012 오전 9시 56분 (몬태나)
그래서 문제는 가짜 라이브러리 (UnderstandingThis.ui.Component1
)가 직접 메타를 할 때 _this
를 사용 (this
로 설정된)와 잘 작동하는 기능이 포함되어 있다는 것입니다 중독 전화. 그 말은 자바 스크립트에서 UnderstandingThis.ui.Component1.performTask1()
을 호출하는 것을 의미합니다. 하지만 문자열 변환을 통해이 동일한 작업을 호출하면 stStringToFunction("UnderstandingThis.ui.Component1.performTask1")()
_this
은 window
을 나타냅니다. 그러나 나에게 그것은 말이되지 않습니다. 나는 자바 스크립트를 1.5 년 동안 해왔으며이 작은 뉘앙스 (Java/C#에서 제공)는 이해하기 어렵다.
무엇이 문제입니까? –
어떤 오류가 있습니까? 질문에 너무 많은 정의가 없습니다. ** humor ++ ** – gdoron
죄송합니다, 오류를 정의 해주십시오. – Michael