나는 지금 자바 스크립트 "클래스"를 테스트하고 있습니다. 필자는 개인 기능의 "this"가 개체 자체를 가리키는 대신 전역 범위 (창)를 가리키고 있음을 확인했습니다.자바 스크립트 : 개인 기능을 호출 할 때 객체 컨텍스트가 손실되었습니다.
왜?
Info : 모드를 비공개로 유지하려는 경우 this.mode 대신 var 모드를 사용합니다. 내부 기능을 모두 비공개로 유지하여 사용자가 액세스 할 수 없도록하려고합니다. 기본적으로 .prototype을 사용하여 private 함수에 액세스하는 myStorage에 공용 함수를 추가합니다.
내 코드 :
var myStorage = function(mymode) {
var mode = mymode;
function privateFunctionA() {
// access this.mode to read mymode from constructor but
// this is pointing to window
};
function privateFunctionB() {
// access this.mode to read mymode from constructor but
// this is pointing to window
};
// check for indexeddb, websql and localstorage
if(mymode == 'A') {
privateFunctionA();
} else {
privateFunctionB();
}
};
myStorage.prototype.publicFunc = function() {
console.log(this.mode); // does this work?
}
var data = new myStorage();
['this] context (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)는 범위와 아무 관련이 없습니다. * 속성 *을 액세스 할 수있는 객체입니다. 그러나'mode'는 생성자에게 private 인 로컬 변수 *입니다. 그래서 NO - 프로토 타입 함수에서 액세스 할 수 없습니다. – Bergi
'this'는 현재 실행중인 함수의 소유자 객체를 참조합니다. 엄밀히 말하면이 경우 프로토 타입 객체이고 myStorage는 아닙니다. – tiguchi