首页 > 解决方案 > 从另一个 .js 文件访问实例属性

问题描述

例如,我想在 HTML 子页面中显示一些统计信息,这些统计信息存储在单击按钮时创建的 Class 对象中。

class Game {
    constructor(start) {
        this.stats = new Statistics();
        this.wallet = new Wallet(start);

        document.querySelector('.start').addEventListener('click', this.startGame.bind(this));
}

例如,我想在另一个子页面上查看来自 stats 变量的统计信息。你能给我一些建议吗?

标签: javascript

解决方案


您可能希望将其存储在全局变量中。

例如(不一定是好的做法):

Game.js

var currentGame = null; 

class Game {

    constructor() {
        currentGame = this;
        this.stats = new Statistics();
        // ....
    }
}

现在,您可以访问您的 currentGame 实例,大概只有其中一个。为了更好地了解如何以更好的方式实现此模式,请研究单例模式。

console.log(currentGame.stats)


推荐阅读