在 JS 中访问父对象的正确方法是什么?
What is the right way to access parent object in JS?
我正在尝试访问 GameManager instance.levels 但总是 returns 未定义。
我不能使用 this.instance 因为它属于 GM
class GameManager {
instance = { levels: { } }
constructor(){
}
Level = class { /* extends ENGINE.Container, ENGINE IS NOT MINE */
constructor(name) {
// super(); /* EXTENDS ENGINE.CONTAINER */
instance.levels[name] = this; /* new ENGINE.Container(); */
}
tick = function(){ /* will be overridden */}
}
}
const game = new GameManager();
var loadScreen = new game.Level('ls');
loadScreen.tick = function(){
}
虽然嵌套 类 本身已经有点 hacky,但您可以更 hackier 并使用 IIFE 将 GameManager
公开为作用域变量:
class GameManager {
instance = { levels: {} }
constructor() {
}
Level = (instance => class {
constructor(name) {
}
getGame = () => instance;
})(this);
}
const game = new GameManager();
var loadScreen = new game.Level('ls');
console.log(loadScreen.getGame());
但同样,最好不要嵌套 类 而是使用工厂方法,例如loadScreen = game.createLevel('ls')
。然后工厂方法可以调用非嵌套版本,如 new Level(game, 'ls')
.
我正在尝试访问 GameManager instance.levels 但总是 returns 未定义。
我不能使用 this.instance 因为它属于 GM
class GameManager {
instance = { levels: { } }
constructor(){
}
Level = class { /* extends ENGINE.Container, ENGINE IS NOT MINE */
constructor(name) {
// super(); /* EXTENDS ENGINE.CONTAINER */
instance.levels[name] = this; /* new ENGINE.Container(); */
}
tick = function(){ /* will be overridden */}
}
}
const game = new GameManager();
var loadScreen = new game.Level('ls');
loadScreen.tick = function(){
}
虽然嵌套 类 本身已经有点 hacky,但您可以更 hackier 并使用 IIFE 将 GameManager
公开为作用域变量:
class GameManager {
instance = { levels: {} }
constructor() {
}
Level = (instance => class {
constructor(name) {
}
getGame = () => instance;
})(this);
}
const game = new GameManager();
var loadScreen = new game.Level('ls');
console.log(loadScreen.getGame());
但同样,最好不要嵌套 类 而是使用工厂方法,例如loadScreen = game.createLevel('ls')
。然后工厂方法可以调用非嵌套版本,如 new Level(game, 'ls')
.