Unable to invoke a function within a JavaScript class

As I develop a THREE.js graphics program, I am looking to create a BodyPart class in Javascript that includes various methods. However, I have encountered an issue where I am unable to successfully call these methods. Despite the code displaying 'calling test', it does not proceed to show 'called test'. I have attempted to move the function test outside of the BodyPart class and link it to the prototype, but the problem persists. Can you help me identify the error in this code?

        function BodyPart (name){        
          this.name = name;
          this.test = function(){
             alert('called test');
             }                
          this.geometry = new THREE.BoxGeometry(1, 1, 1);
          this.material = new THREE.MeshNormalMaterial( { color: 0x00ff00 } );            
          return new THREE.Mesh(this.geometry, this.material);
          }


        var backFoot = new BodyPart("Back foot");
        alert('calling test');          

        backFoot.test();

Answer №1

The issue lies in the fact that you are returning a THREE.mesh from your function:

return new THREE.Mesh(this.geometry, this.material);

To resolve this, consider making mesh a property instead:

this.mesh= new THREE.Mesh(this.geometry, this.material);

Answer №2

The reason for this issue is that you are returning a THREE.Mesh from the function and storing it in backFoot. As a result, you are essentially attempting to execute:

new THREE.Mesh(this.geometry, this.material).test();

However, by calling test in this way:

backFoot.text();

This results in an error because THREE.Mesh does not have the test function. Instead of returning from the function, it is advisable to set it as a property:

function BodyPart(name) {
  this.name = name;
  this.test = function() {
    alert('called test');
  }
  this.geometry = new THREE.BoxGeometry(1, 1, 1);
  this.material = new THREE.MeshNormalMaterial({
    color: 0x00ff00
  });
  this.mesh = new THREE.Mesh(this.geometry, this.material); //Now, as a property instead of returning.
}

var backFoot = new BodyPart("Back foot");
alert("calling test");
backFoot.test();
//Access the mesh with backFoot.mesh
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r70/three.min.js"></script>

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

Where is the appropriate location to insert a <script> tag in NextJs?

I am facing a challenge in my NextJs application when trying to include the <script> code. I attempted to add it in a .js file but it did not work as expected. In traditional React applications, we typically use the index.html file to incorporate sc ...

locate the following div using an accordion view

Progress: https://jsfiddle.net/zigzag/jstuq9ok/4/ There are various methods to achieve this, but one approach is by using a CSS class called sub to hide a 'nested' div and then using jQuery to toggle the Glyphicon while displaying the 'nest ...

Working with Java to parse non-strict JSON data that does not have keys enclosed in quotes

I am currently facing the challenge of parsing a string in JSON format where keys are not enclosed in quotes. While I have successfully parsed this string in Javascript, I am struggling to find a Java API that can assist me with parsing. The APIs I have at ...

Issues with the initial calculator project I built using JavaScript (excluding HTML and CSS)

My first calculator is nearly complete, but I have encountered a challenge. The functionality of my calculator is quite simple; it prompts the user for input using window.prompt and performs addition, subtraction, multiplication, or division based on the u ...

Explore button that gradually decreases max-height

I have a "Show More" button that expands a div by removing the css attribute max-height, but I want to add an animation similar to jQuery's slideToggle() function to smoothly reveal the rest of the content. This is the code I am using: <div id="P ...

Encountering an Issue Retrieving User Orders - Receiving 401 (Unauthorized) Status Code

I am currently working on a React project focused on displaying user orders. I have successfully integrated JSON Web Tokens (JWT) for user authentication. However, I keep encountering a persistent 401 (Unauthorized) error when trying to retrieve the user&a ...

The issue of underscorejs being undefined arises when trying to load it using both XMLHttpRequest and

I am attempting to dynamically load underscorejs using XMLHttpRequest and eval function function includeScriptSync(scriptUrl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", scriptUrl, false); xmlhttp.onreadystatechange = function() ...

Can you explain the functionality of this code snippet from a slate.js demonstration?

Trying to grasp the concepts of Slate.js, I delved into the rich text example. Within it, I encountered a code snippet that has left me puzzled. const isBlockActive = (editor, format) => { const [match] = Editor.nodes(editor, { match: n => ...

How can the total price for a shopping cart be computed in React/Redux?

After extensive searches on Google and SO, I'm still coming up empty-handed when it comes to calculating the total price of items in a cart. Many tutorials stop at basic cart functionalities like "Add item to cart" or "increase/decrease quantity", but ...

JSON data displaying improper date format

After retrieving date from the database, it is in the following format: {5/13/2002 12:00:00 AM} Once this is passed as JSON and bound to a textbox, it appears like this: /Date(1021228200000)/ Is there a way to display the date in the correct format? E ...

Orbit Control is experiencing issues with initialization

I'm attempting to create a three.js STL model viewer using code. Here is the code snippet: <!-- prerenderer --> <!doctype html> <html> <head> <title>Enjoy your model</title> <meta charse ...

Unlock the Power of TWBS Ratchet: Manually Closing Modal Windows

Currently, I am in the process of developing a mobile web application using Ratchet. The main task at hand involves opening a modal, filling out a form, clicking a button to save the input data, and then closing the modal. Although I have managed to close ...

Text-field input experiencing issues with placeholder display

As a beginner in Angular, I may make some mistakes. I created a textField input using a directive in Angular: .directive('textField', function () { return { restrict: 'E', scope: true, require: 'ngModel ...

The animation for the CSS gradient background is failing to animate

After finding a similar code snippet used for backgrounds, I made some modifications to suit my needs. However, when attempting to implement it or any animation, nothing seems to be working. Even simple animations are not functioning as expected. While I a ...

What is the best method for inserting a line break into a string?

Can you please explain how I can insert a line break into a string with JavaScript? I have tried using the <br/> tag, but it's not working. What is the correct way to achieve this? JavaScript var str="Click Here" +"<br>"+ "To Set" +"< ...

Utilizing JavaScript or jQuery to adjust the cursor pointer value based on user input

Issue: Need help with live updating of input value to range input pointer [Check out my CodePen for reference][1] Adjust upper range input pointer based on lower range input pointer ][2] I am currently working on a range-to-range calculator for a book ...

JavaScript counter to monitor the number of requests made to the Open Weather Map API

Currently, I am utilizing the Open Weather Map's free API which allows me to make 1000 API calls per day through their One Call API. However, there is no built-in feature for tracking these calls in the Open Weather Map platform. To address this issue ...

Showing real-time information from an object

I am attempting to showcase the 'helpText' data on the front end based on the type. Is it feasible to include a conditional statement (metricsType variable) and the [key] value into what I want to return? The final 'p' below provides an ...

Is Grouping Together Installed Private Modules Possible?

Exploring a modular JavaScript approach in my upcoming project is a new concept for me. I would prefer explanations to be simple due to my limited experience. I have uploaded my private package on npm: @name/package-name The private package contains mul ...

How to toggle code block visibility in Angular's ngOnInit() method

I'm currently analyzing different design patterns to optimize the number of REST calls when implementing a 'save while typing feature'. To provide a general overview, in my ngOnInit() function, I have included the following code snippet (wit ...