dongzen5577 2019-06-07 04:12
浏览 54
已采纳

如何全局访问JavaScript对象

I am creating a JavaScript based game with PHP, and need help storing the user's account object. Once I construct the player object in JavaScript, how can I use this object throughout every page?

I have tried to add the user's account object to the window object, but did not have any luck. This code is placed in the menu which is used on all pages.

 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>';
 }

Each time a page is loaded, a new player is created and added to the window object. I expected "window.user" to be defined after adding the user's account object.

Here is my Player object constructor as well

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条回答 默认 最新

  • duandianwen1723 2019-06-07 09:13
    关注

    Use local storage to store value:

    localStorage.setItem('test', 1);
    

    And get the value later:

    localStorage.getItem('test')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统