은과 같이 구성 실패 :자바 스크립트 - 외부 함수를 호출 할 때 폐쇄는
let Game = function() {
let privateVar;
// private would be an example private variable assigned later
// Other private variables go here
return {
Engine: function() {
// More specific private variables
init: function() {
privateVar = this.sampleValue;
// Game.Engine.sampleValue doesn't help either
// Start up everything, for example, calling a Graphics method:
Game.Graphics.method1();
},
sampleValue: 10,
// Other methods
}
Graphics: Graphics()
}
}
function Graphics() {
// Visuals-specific private variables
return {
method1: function() {
console.log(privateVar);
// This would complain about the variable not being defined
}
// methods
}
}
Game.Engine.Init();
아이디어는 Graphics
에 Graphics()
함수를 호출하여 내부 코드에서 시각적 코드를 분리하는 것입니다 메서드 (예를 들어, Graphics()
함수를 별도의 파일로 빌드 할 수 있습니다). 그러나 이것을 수행 할 때 Graphics
메서드는 내가 처음 선언 한 private 변수를 잃어 init
메서드에서 할당되고 Graphics
의 메서드에 의해 호출 될 때마다 Uncaught ReferenceError: private is not defined
을 출력합니다.
나는 한 솔루션이 단지 Graphics()
에있는 해당 개인을 재 할당하는 것 같지만, 그 목적은 다소 어긋납니다. 누구나 더 좋은 아이디어가 있습니까? 미리 감사드립니다.
편집 : 당신이 private 변수는 사용자의 그래픽 유형에 액세스하지 않아야합니다 내가
see mozilla reference
나는 당신이이 같은 JS 클래스를 생성해야한다고 생각 실제 질문. 기대했던 것처럼 작동하지 않는 것이 있습니까? 그렇다면 재현 가능한 예를 제공해주십시오. – abl
위에 제시된 코드 스 니펫은 구문 적으로 잘못되었습니다. 그것을 수정하십시오. – alicanerdogan