Why aren't methods for JavaScript objects being identified as expected?

My current project involves creating an avatar that follows the movement of my mouse.


After successfully developing a functional avatar, I'm now looking to replicate it using an object constructor. The only difference is that instead of var angleToBe;, I use this.angleToBe;. Everything is directly linked to the constructor, but I encountered a problem when constructing the methods, particularly the turnToMouse function. Here's how my syntax looks:

Avatar.prototype.turnToMouse = function() {
  if (this.canTurn) {
    this.spotX = this.body.position.x;
    this.spotY = this.body.position.y;
    this.spotY = this.spotY * -1 + height;
    this.body.angleToBe = Math.atan2(cursorX - this.spotX, cursorY - this.spotY);
    this.body.__dirtyRotation = true;
    this.body.__dirtyPosition = true;
    this.gun.__dirtyRotation = true;
    this.gun.__dirtyPosition = true;
    this.body.rotation.set(0, 0, avatarAngleToBe);
  }
  setTimeout(this.turnToMouse, time);
};

The constructor used is for Avatar.

This function continuously adjusts the position of the avatar and its gun towards the direction of the mouse. It should work without issues since it mirrors my existing working function perfectly, except for the added this references.

The trouble arises when I include this code within the constructor (function Avatar() {}):

this.turnToMouse();

Here, the editor fails to recognize the function 'turnToMouse()' despite its existence.

Can anyone spot what might be missing in this setup?

PS: If you'd like to view the complete code with the operational avatar and the object avatar, simply click on this link using Google Chrome.

Answer №1

One interesting feature of JavaScript is known as hoisting, where certain statements are moved to the top of the current scope.

In this case, your function Avatar(...) { ... } declaration is hoisted to ensure it is available when you create a new instance with new Avatar(...). If this hoisting didn't occur, the code would fail because the Avatar function wouldn't have been defined yet.

The problem arises when not all aspects of the code are hoisted. The assignment of Avatar.prototype.turnToMouse occurs after calling new Avatar(...), meaning the method doesn't exist at that point in the execution.

To resolve this issue, it's essential to assign all Avatar.prototype properties before calling new Avatar(...).


Additionally, there may be issues with this binding in relation to the setTimeout call. To correct this, modify the code as follows:

var avatar = this;
setTimeout(function () { avatar.turnToMouse(); }, time);

For more information on why this change is necessary, refer to resources discussing function binding/context.

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

Having difficulty toggling a <div> element with jQuery

I am attempting to implement a button that toggles the visibility of a div containing replies to comments. My goal is to have the ability to hide and display the replies by clicking the button. The "show all replies" button should only appear if there are ...

Processing multipart form data in a Node.js Express application

I am encountering an issue with sending form data from a reactjs app using axios. Even though the express is properly configured, the req.body appears to be empty. What could be causing this problem? import bodyParser from 'body-parser'; app.use ...

Angular's directives do not trigger the 'viewContentLoaded' event

I recently created a 'light-gallery' directive that relies on the jquery.lightgallery.js plugin to initialize the $.fn.lightGallery() functions. It is crucial for these functions to be executed after the directive template has been compiled and l ...

Exploring the Depths of React by Cycling Through Arrays in Tabular Format

One issue I'm facing is that I have an array named paymentMethods which I'd like to iterate through in tabs. However, I seem to be struggling with the iteration part. To take a closer look at my code, please visit my codesandbox HERE <div& ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Error: a is missing in the Google Maps configuration

I'm looking to integrate Google Maps into my program, but I've encountered an error stating that 'a is null' when using a variable in the Google Maps API. Below is my current implementation: //Creates a new center location for the goog ...

I'm looking to create a unique combination of a line and bar chart. Any advice on how to

When I stretch my Scale like this determineDataLimits: function () { var min = Math.min.apply(null, this.chart.data.datasets[0].data) console.log(this) console.log(defaultConfigObject) Chart.options.scales.rightSide.ticks.min = function ...

AngularJS not refreshing the view

I'm having an issue in my app where I calculate the total bill and display it on my view. The first time, everything works fine. However, when I increment the $scope.bill_total, the view is not updating even though I can see the change in the console. ...

Unable to update cube textures at runtime using Three.js r59

I managed to create a cube using the canvas renderer with r59 of Three.js, and it has different textures on different sides, which renders fine. I can also animate this cube's position and rotation without any issues. Now, here's what I'm t ...

Can someone guide me on how to display only the most recent form submission in a form using React and JavaScript? Appreciate your help

Currently, I'm facing a challenge with displaying the latest form submission below a form on my page. Instead of showing all form submissions, I only want to display the most recent one. I'm seeking advice on how best to tackle this issue. If it ...

Is it possible to implement an SSL certificate with my Next JS deployment?

Currently, I am running a Next.js deployment on an EC2 instance and looking to secure it with an SSL certificate. My initial thought was to use a custom server config for this purpose, but I'm concerned that it may impact certain optimizations that I& ...

Loading of iframes occurs only after receiving the content sent through the postMessage function

I have a scenario where an iframe is used to receive information through the contentWindow.postMessage function in order to log in to a page that I am creating. However, I am facing an issue where the page loads before the contentWindow.postMessage message ...

Utilizing Jquery to extract an array from a nested array or object within JSON

When receiving JSON formatted data where objects can be nested inside other objects or arrays, I need to extract specific values and append them on a function click. var result={ "diagnosis":{ "Diagnosis":{ "head":"Diagnosis", "head_id": ...

How can I display a timer icon in front of text on a Material-UI CardHeader subtitle?

I have a question regarding displaying time in my posts. Currently, I am showing the time as 'a few seconds ago', '2mins ago', 'an hour ago', etc. However, I would like to include a clock icon before this string. Although I a ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

Display Descriptions Upon Hovering Over Images

I am attempting to utilize JavaScript to display the caption of an image only when it is being hovered over, and to have a default caption shown when no image is being hovered. <ul class="logos"> <li class="image-1"></li> <li ...

Top method for constructing a JSON object by combining data from two queries and a joining table

Currently, I am developing a small webservice in Node.js to handle commands in a restaurant using Express.js. In my database, I have the following tables: DISH(id,name) COMMAND(id,table,status) COMMAND_DISH(idCommand,idDish,quantity) I am interested in ...

Node.js tutorial: Fetching all pages of playlists from Spotify API

Currently, I am attempting to retrieve all of a user's playlists from the spotify API and display them in a selection list. The challenge lies in only being able to access 20 playlists at a time, which prompted me to create a while loop utilizing the ...

Tips for transferring a dataTable from C# code behind to jQuery

I am trying to pass a string as a table of data from C# code behind to jQuery using two functions: C# [System.Web.Services.WebMethod(EnableSession = true)] public static List<ListItem> GetImageArray(string AccNo) { string result = string.Empty; ...

Removing multiple data rows in JSP using AJAX by selecting check boxes

I have a requirement where I need to store a list of objects (each with a unique id) as a session parameter. These objects are then displayed in a table in a JSP using JSTL. <c:forEach var="list" items="${PlayerList}"> <tr> <td> ...