目前,我正在做一個小遊戲結構類似這樣:的Javascript - 閉幕遇事調用外部函數時
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
方法會丟失我在開始時聲明並在init
方法中分配的私有變量,並在Graphics
中的某種方法調用Uncaught ReferenceError: private is not defined
時拋出該變量。
我想一個解決方案只是重新分配在Graphics()
這些私人,但這會有點殺死的目的。任何人有更好的主意?提前致謝。
編輯:使代碼更容易一點了解我在
這不是我清楚什麼是你的實際問題。有沒有像你期望的那樣工作?如果是這樣,請提供一個可重現的例子。 – abl
上面給出的代碼片段是語法錯誤的。請糾正這一點。 – alicanerdogan