如何全局访问JavaScript对象

时间:2019-06-07 04:12:56

标签: javascript php

我正在用PHP创建基于JavaScript的游戏,并且需要帮助来存储用户的帐户对象。用JavaScript构建播放器对象后,如何在每个页面中使用该对象?

我试图将用户的account对象添加到window对象,但是没有任何运气。此代码位于所有页面上使用的菜单中。

 if (isset($_SESSION['userId'])) {
        $user = $_SESSION['user'];
        echo '<script>                 
        if (typeof window.user != "undefined") {
            console.log("user is defined from before.");
            console.log(window.user);
        } else {
            var user = new Player('.$user->{'id'}.',"'.$user->{'username'}.'");
            window.user = user;
            console.log("A new user was created.");
            console.log(window.user);
        }</script>';
 }

每次加载页面时,都会创建一个新的播放器并将其添加到window对象。我希望在添加用户的帐户对象之后定义“ window.user”。

这也是我的Player对象的构造函数

function Player (id, username) {
this.id = id,
this.username = username,
this.resources = {
    hydrogen: 0,
    helium: 0,
    carbon: 0,
    nitrogen: 0,
    oxygen: 0,
    sodium: 0,
    magnesium: 0,
    aluminium: 0,
    silicon: 0,
    sulfur: 0,
    calcium: 0,
    titanium: 0,
    cobalt: 0,
    nickel: 0,
    copper: 0,
    krypton: 0,
    palladium: 0,
    silver: 0,
    platinum: 0,
    gold: 0
},
this.currency = {
    currency1: 0,
    currency2: 0,
    currency3: 0,
    currency4: 0,
    currency5: 0
},
this.starter = 0

}

1 个答案:

答案 0 :(得分:0)

使用本地存储来存储价值:

localStorage.setItem('test', 1);

稍后获取值:

localStorage.getItem('test')