"Attempting to call a function on a JavaScript object is not allowed

I am currently working on creating a Pong game using JavaScript. Within my Game object, I am utilizing the prototype property to define various methods. However, I have encountered an error message stating "Undefined is not a function". This error specifically occurs within the Game.prototype.step function, where it seems that this.update is undefined. Below is the code snippet for the Game object:

(function(root) {
  var Pong = root.Pong = (root.Pong || {});

  var Game = Pong.Game = function() {
    this.canvas = document.getElementById('canvas');
    this.canvas.width = 800;
    this.canvas.height = 400;
    this.context = canvas.getContext('2d');
    this.maxStartSpeed = 10;
    this.keysDown = {};
    this.player2 = new Pong.Player({'player': 2});
    this.player1 = new Pong.Player({'player': 1});
    this.ball = new Pong.Ball(400, 200);
  }

  Game.prototype.update = function() {
    this.player1.update();
    this.player2.update();
    this.ball.update(player1.paddle, player2.paddle);
  };

  Game.prototype.render = function() {
    this.context.fillStyle = "#bdc3c7";
    this.context.fillRect(0, 0, width, height);
    this.player1.render();
    this.player2.render();
    this.ball.render();
  };


  Game.prototype.animate =  function(callback) { 
    window.setTimeout(callback, 1000/60) 
  };

  Game.prototype.step = function() {
    this.update();
    this.animate(this.step);
  };

  window.addEventListener("keydown", function (event) {
    Game.keysDown[event.keyCode] = true;
  });

  window.addEventListener("keyup", function (event) {
    delete Game.keysDown[event.keyCode];
  });

  window.onload = function() {
    document.getElementById('canvas-container').appendChild(canvas);
    game = new Game();
    game.animate(game.step);
  };  

})(this);

Answer №1

If you want to maintain the proper scope when using setTimeout, you should utilize the bind method.

Replace

this.animate(this.step);

with

this.animate(this.step.bind(this));

Make sure to apply the same technique to the other animate calls as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building a JavaScript application with Node.js and MySQL to seamlessly interact with both offline and online databases

As I develop a JavaScript web-app, my plan is to utilize Node.js for connecting the app with an existing MySQL database. My initial question pertains to the structure of the Node code: should it be written in the same .js file as my application or kept se ...

Learn how to dynamically assign an image property as the src attribute on an asynchronous object in Vue

I am still new to Vue and navigating my way through the learning process. I have been able to successfully fetch data from an endpoint, which is returned as an object. The object is making it into the component as verified by both the devtools and on the p ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

What is the best way to extract a portion of a JSON string?

this.on('success', function(file, responseText) { var theID = JSON.stringify(responseText); alert(theID); window.location.href = ('want to put something here'); }); The ...

Error: Unable to initialize monthSelectPlugin as a constructor while trying to utilize the Flatpickr plugin

I'm trying to incorporate the monthSelectPlugin for flatpickr in a Rails application. I have it specified in my importmap like this: pin "flatpickr/dist/plugins/monthSelect", to: "https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/emai ...

Retrieving cookie from chrome.webRequest.onBeforeSendHeaders

I have been developing a Firefox add-on with the goal of intercepting HTTP requests and extracting the cookie information. While I was successful in extracting the 'User-agent' data from the header, I faced difficulties when attempting to extract ...

Tips for properly formatting quotes in JSON to activate a link

I am working with a JSON configuration file that looks like this: "type": "script", "label": "coreapps.archivesRoom.printSelected", "script": "emr.fragmentActionLink(${project.parent.artifactId},\"downloadPatientHistory\", &bs ...

Is it possible to have Bootstrap 3 Navigation Tabs positioned at both the top and bottom of a

While working on a Bootstrap 3 website, I discovered that it is possible to have both a top nav-tab and bottom nav-tab section on the same page. These two distinct tab menus can control the display of the same tab content areas. However, I encountered an ...

The collapsible section expands upon loading the page

Trying to implement Disqus as a plugin on my test webpage, I created a collapsible section with a "Show comments" button. The idea was to hide the plugin by default and reveal it only when users click on "Show comments". Despite using the w3schools example ...

JavaScript and modifying color using hexadecimal color codes

Being a novice in front-end development, I embarked on a project using JavaScript that would alter the color of a div based on environmental parameters such as temperature and pressure. My initial idea involved creating buttons to adjust the temperature - ...

A step-by-step guide on generating an HTML table from JSON information

Hi there, I'm looking to create a table format using JSON data. Here is an example of the JSON data: var jsondata = [ { id: 1, name: 'Mani', subject: 'English', Score: 88 }, { id ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

`Custom transitions between sections using fullpage.js`

Has anyone used the fullpage.js extension to achieve an animation similar to this one, where sections are destroyed on scroll? ...

When configuring Webpack with a rule array, JSX is not properly recognized by the tool

Here is the configuration for my webpack setup: const path = require('path'); module.exports = { entry: './src/entry.jsx', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist&ap ...

The drop-down menu continually moves in an erratic manner

These are the functions I have created: function showDropdown() { $(".dropdownitem").show('slow'); } function hideDropdown() { $(".dropdownitem").hide('slow'); } Below is the code for my drop-down menu: <div id="dropdown" ...

How can I pass a specific value, rather than the entire array, in a ReactJS dropdown menu?

I am facing a problem where the entire array is being passed as an argument when I call onchange after getting correct values in the dropdown. Instead of only receiving the selected value, e contains the whole array. Here is the code snippet that demonst ...

The jQuery dynamic fields vanish mysteriously after being validated

I am facing an issue with my jQuery and validation. Below is the code snippet causing the problem: var fielddd = 1; $(document).on('click', '.btn.add-field', function() { fielddd++; $('#newfield').append('< ...

javascript popup appears twice in IE when using PHP

After testing this script on multiple browsers, an issue arises when using IE. In all other browsers, the form submission alert only appears once. However, in Internet Explorer, the alert pops up twice. What could be causing this discrepancy? <!DOCTYP ...

Encountering the error message "Unable to access /" on the browser when using express router

Just started working with the express Router for the first time. Here is my route.js: var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('home page'); }); module.e ...

What is the best way to show JavaScript output with span style?

I have added a translation feature that allows users to switch paragraphs to French when clicked. Each paragraph now has the first word wrapped in a span with a CSS class that enlarges and colors the text. However, I am facing an issue where when switchi ...