这在 Phaser 游戏 JS 中

this in Phaser game JS

所以我最近开始学习 JS,现在尝试使用 Phaser 来制作游戏。 在下面的代码中,

1- 作者使用 "this" 指的是 mainState 吗? 2- 没有为 bird 定义变量。那么它在哪里存储数据??

// Initialize Phaser, and creates a 400x490px game
var game = new Phaser.Game(400, 490, Phaser.AUTO, 'gameDiv');

// Creates a new 'main' state that will contain the game
var mainState = {

    // Function called first to load all the assets
    preload: function() { 
        // Change the background color of the game
        game.stage.backgroundColor = '#71c5cf';

        // Load the bird sprite
        game.load.image('bird', 'assets/bird.png');  

        // Load the pipe sprite
        game.load.image('pipe', 'assets/pipe.png');      
    },

    // Fuction called after 'preload' to setup the game 
    create: function() { 
        // Set the physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        // Display the bird on the screen
        this.bird = this.game.add.sprite(100, 245, 'bird');

        // Add gravity to the bird to make it fall
        game.physics.arcade.enable(this.bird);
        this.bird.body.gravity.y = 1000; 

        // Call the 'jump' function when the spacekey is hit
        var spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        spaceKey.onDown.add(this.jump, this); 

        // Create a group of 20 pipes
        this.pipes = game.add.group();
        this.pipes.enableBody = true;
        this.pipes.createMultiple(20, 'pipe');  

        // Timer that calls 'addRowOfPipes' ever 1.5 seconds
        this.timer = this.game.time.events.loop(1500, this.addRowOfPipes, this);           

        // Add a score label on the top left of the screen
        this.score = 0;
        this.labelScore = this.game.add.text(20, 20, "0", { font: "30px Arial", fill: "#ffffff" });  
    },
您发布的代码中的

this 指的是您推断的 mainState 。使用 this.valueName 在 mainState 对象上创建一个新值。

请参阅 this link 了解有关 this 关键字的更多信息以及它在不同地方使用时所指的内容。链接页面中的这个示例与您的代码相关:

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37

它像往常一样存储数据,就所有意图和目的而言,它执行的功能与正常情况下在函数外添加另一个值相同。并且可以通过 mainState.bird.

访问
var mainState = {
    bird : game.addBird(...)
}
  1. 是的,mainState对象函数中的this关键字指向mainState对象本身。

  2. bird 变量是在 mainState 对象本身上定义的:

    // Display the bird on the screen
    this.bird = this.game.add.sprite(100, 245, 'bird');