javascript 层.更新不是一个函数?

y3bcpkx1  于 2023-08-02  发布在  Java
关注(0)|答案(3)|浏览(90)

我是JavaScript新手,所以我参加了YouTube课程,试图学习更多。当我开始制作一个无限滚动的背景时,我得到了错误'TypeError:layer.update不是控制台中的函数,这是滚动器代码

class Layer {
  constructor(game, width, height, speedModifier, image) {
    this.game = game;
    this.width = width;
    this.height = height;
    this.height = speedModifier;
    this.image = image;
    this.x = 0;
    this.y = 0;
  }
  update() {
    if (this.x < -this.width) this.x = 0;
    else this.x -= this.game.speed * this.speedModifier;
  }
  draw(context) {
    context.drawImage(this.image, this.x, this.y, this.width, this.height);
  }
}

export class Background {
  constructor(game) {
    this.game = game;
    this.width = 1667;
    this.height = 500;
    this.layer5image = document.getElementById("layer5");
    this.layer1 = new Layer(
      this.game,
      this.width,
      this.height,
      1,
      this.layer5image
    );
    console.log(this.layer5image);
    this.backgroundLayers = [layer1];
  }
  update() {
    this.backgroundLayers.forEach(function (layer) {
      layer.update();
    });
  }
  draw(context) {
    this.backgroundLayers.forEach((layer) => {
      layer.draw(context);
    });
  }
}

const b = new Background();
b.update();

字符串
我试着问ChatGPT,我认为这会有帮助,它没有,相反,它告诉我添加箭头语法,我已经这样做了。在那之后,我看了看微软的智能感知(或无论它叫什么),并将其更改为匿名函数(或类似的东西),老实说,我没有期望任何事情,什么也没有发生

z8dt9xmd

z8dt9xmd1#

在你的Background的构造函数中,你使用初始化this.layer1作为一个层,然后使用layer1,没有this,使其未定义,因此,它无法找到update
下面是正确的代码:

constructor(game){
    this.game = game;
    this.width = 1667;
    this.height = 500;
    this.layer5image = document.getElementById('layer5');
    this.layer1 = new Layer(this.game, this.width, this.height, 1, this.layer5image)
    console.log(this.layer5image);
    this.backgroundLayers = [this.layer1]; // `layer1` is a property of `this`
}

字符串

l2osamch

l2osamch2#

我在分配BackgroundLayer时犯了一个错误,导致它未定义(您可以在MrDiamond的答案中找到更多细节)

yizd12fk

yizd12fk3#

可以使用构造函数
这里有一个例子

function Background(game, width) {
    this.game = game
    this.width = width
    this.update = function() {
        // Your Code Here
        console.log("It's A Update Function");
    }
}

// Don't forget to add new keyword
const background = new Background("Kat Game", 100)

// Call
console.log("Game : ", background.game)
background.update()

// Output
// Game : Kat Game
// It's A Update Function

字符串

相关问题