Что я пытаюсь сделать:
Я пытаюсь кодировать Flappy Bird с библиотекой p5.js.
Проблема: Функция не распознает функцию, которую я определил.
function Game() {
this.pipes = generatePipes();
setInterval(this.gameLoop, 1000 / 60);
generatePipes = () => {
const firstPipe = new Pipe(null, space);
const secondPipeHeight = winHeight - firstPipe.height - space;
const secondPipe = new Pipe(secondPipeHeight, space);
return [firstPipe, secondPipe]
}
gameLoop = () => {
this.update();
this.draw();
}
update = () => {
if (frameCount % 30 == 0) {
this.pipes = this.generatePipes();
this.pipes.push(...pipes);
}
this.pipes.forEach(pipe => pipe.x = pipe.x - 1);
}
draw = () => {
this.pipes.forEach(pipe => pipe.draw());
}
}
class Pipe {
constructor(height, space) {
this.x = 100;
this.y = height ? winHeight - height : 0; // borunun y eksenine göre konumunu belirler
this.width = pipeWidth;
this.height = height || minPipeHeight + Math.floor(Math.random() * (winHeight - space - minPipeHeight * 2));
}
draw() {
fill(124);
noStroke();
rect(this.x, this.y, this.width, this.height);
}
}
ошибка:
Uncaught TypeError: this.generatePipes is not a function



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


То, как вы это написали: вы назначили функцию переменной generatePipes, что означает, что вы можете получить к ней доступ только после создания экземпляра переменной.
У вас есть два варианта: создать экземпляр переменной generatePipes перед ее использованием или объявить ее как подфункцию.
function Game() {
generatePipes = () => {
...
return x;
}
this.pipes = generatePipes();
}
ИЛИ
function Game() {
this.pipes = generatePipes();
function generatePipes() {
...
return x;
}
}
function Game() {
generatePipes = () => {
const firstPipe = new Pipe(null, space);
const secondPipeHeight = winHeight - firstPipe.height - space;
const secondPipe = new Pipe(secondPipeHeight, space);
return [firstPipe, secondPipe]
}
gameLoop = () => {
this.update();
this.draw();
}
this.pipes = generatePipes();
setInterval(this.gameLoop, 1000 / 60);
update = () => {
if (frameCount % 30 == 0) {
this.pipes = this.generatePipes();
this.pipes.push(...pipes);
}
this.pipes.forEach(pipe => pipe.x = pipe.x - 1);
}
draw = () => {
this.pipes.forEach(pipe => pipe.draw());
}
}
Этот обновленный код должен работать. В вашем коде, поскольку вы вызвали generatePipes() перед выражением вашей функции, это не сработает. Функциональные выражения загружаются только тогда, когда интерпретатор достигает той строки кода, где вы впервые определили свое функциональное выражение.
Просто назначьте свои функции this:
this.generatePipes = () => {...}
this.gameLoop = () => {...}
this.update = () => {...}
this.draw = () => {...}
У вас есть функциональное выражение с анонимной стрелочной функцией, а не объявление функции. так что не поднимается наверх. Глобальная переменная
generatePipesпо-прежнему равна нулю, когда вы вызываете функцию. Поэтому либо переместитеgeneratePipesв прототип и используйте экземпляр игры, либо определите generatePipes перед его вызовом.