Create a variable within a nested function and assign it to the outer scope

I'm struggling to get this code up and running due to some issues with function scopes.

Here is the current state of my code:

var Canoe = function () {
    this.mesh = new THREE.Object3D();
    var loader = new THREE.JSONLoader();
    loader.load( 'models/canoe.json', function ( geometry, materials ) {
        var canoeMesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ));
        canoeMesh.castShadow = true;
        canoeMesh.receiveShadow = true;
        this.mesh.add(canoeMesh);
    });

}

This is the error message I keep encountering:

Cannot read property 'add' of undefined

Is there a way for me to properly assign the inner function's created mesh to the outer variable?

Answer №1

To solve this issue, one approach is to store the mesh in a variable within the function:

var Boat = function () {
var mesh = new THREE.Object3D();
this.mesh = mesh;
var loader = new THREE.JSONLoader();
loader.load( 'models/boat.json', function ( geometry, materials ) {
    var boatMesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ));
    boatMesh.castShadow = true;
    boatMesh.receiveShadow = true;
    mesh.add(boatMesh);
});

Exploring how this behaves in javascript could fill entire chapters. Understanding it may not be straightforward as expected.

Answer №2

Prior to calling loader.load(), include the following:

const self = this;

Within your load function, insert the following line of code:

self.mesh.add(canoeMesh);

The issue stems from "this" having a different reference within loader.load() compared to outside of the function.

Answer №3

There are a few ways to approach this situation. One option is to assign the value of this to another variable, as shown below:

var self = this;
var Boat = function () {
    self.mesh = new THREE.Object3D();
    var loader = new THREE.JSONLoader();
    loader.load( 'models/boat.json', function ( geometry, materials ) {
        var boatMesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ));
        boatMesh.castShadow = true;
        boatMesh.receiveShadow = true;
        self.mesh.add(boatMesh);
    });
}

Alternatively, if you're using a transpiler, you could use an arrow function which preserves the context of this:

var Boat = () => {
    this.mesh = new THREE.Object3D();
    var loader = new THREE.JSONLoader();
    loader.load( 'models/boat.json', function ( geometry, materials ) {
        var boatMesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ));
        boatMesh.castShadow = true;
        boatMesh.receiveShadow = true;
        this.mesh.add(boatMesh);
    });
}

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

React: Avoid the visible display of conditional rendering component fluctuations

In my current React project, I am developing a page that dynamically displays content based on the user's login status. The state variable "loggedIn" is initially set to null, and within the return statement, there is a ternary operator that determine ...

Tips for consolidating outputs from three different APIs using JavaScript and AJAX? [Pseudo code example]

For my school project, I am working on an e-commerce aggregator site where I need to combine product data from 3 different APIs (like Aliexpress and Amazon) into one homepage. Although I can retrieve results from each API individually, I'm facing chal ...

"Unexpected behavior: NextAuth is failing to return defined custom scopes

I am currently working on a NextJS project that utilizes NextAuth. Initially, everything was functioning properly with the default scopes. However, my project now requires additional claims, which are listed in the supported scopes here. "scopes_supporte ...

Dealing with the Windows authentication popup in Protractor

I recently started using Protractor and encountered a problem with managing the authentication popup. I have included a screenshot for reference. If anyone has a solution, please advise me on how to resolve this issue. Thank you in advance. ...

The reducer and the store are experiencing a lack of synchronization

I'm having trouble figuring out what's going on with my json file that contains a list of products. I'm trying to render specific ones, but it's not working as expected. Here's the reducer code I'm using: export default(stat ...

Tips for successfully sending data to an ng-include controller

So, I've got this ng-include html element, and I'm trying to figure out how to pass data from an external source to the controller. The primary controller is responsible for fetching json data from a http webservice, and then parsing that data i ...

Running JavaScript within Objective-C in a Cordova plugin

I'm working with cordova version 6.5.0 and I'm trying to develop a plugin that can execute some javascript code. I've read on various forums that I can use stringByEvaluatingJavascriptFromString method in my webview, but it seems like it&ap ...

Javascript: regular expression to validate alphanumeric and special characters

Looking to create a regular expression for a string (company/organization name) with the following conditions: No leading or trailing spaces No double spaces in between Shouldn't allow only a single character (alphanumeric or whitelisted) Can start ...

Iterating through AJAX response using jQuery on Button Click

I am a newcomer to the world of coding and have been struggling for hours to solve this particular issue: After making an AJAX call, I receive a Json two-dimensional array jqXHR[][]. The first index represents each product ID, while the second one contain ...

Determining the data type of a textbox value in JavaScript: String or Number?

I am encountering an issue with the code below: <input type="text" value="123" id="txtbox"> <script> var myVar = document.getElementById('txtbox').value; if (myVar.substring) { alert('string'); } else{ alert('number&a ...

Functionality that can be utilized repeatedly

I've been struggling to implement a feature for repeatable blocks in my web form. The issue I'm facing is that when I click the buttons, nothing happens even though they work fine when tested in the console. I've been stuck on this problem f ...

Using NodeJS to assign key-value pairs to a JSON object

I am currently working with a NodeJS script that receives data in the form of "key, value" pairs and I need to transform this data into a JSON object. The data is obtained using SNMP where the key corresponds to the OID. My goal is to efficiently map thes ...

Is there a way to merge arrays in jQuery by pushing one array into another?

I am looking to construct an array as shown below. var coordinates = [ [41.02178, 29.26108], [41.02196, 29.26067], [41.02251, 29.26031], [41.02258, 29.26015], [41.02267, 29.25926] ]; My attempt in the code was as follows: var locations = []; f ...

Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader. Let's take a look at some key portions of the code: webpack-config.js: const path = require("path"); const nodeExte ...

Tips on navigating the scroller vertically as the user interacts with a selected div by scrolling up and down

On my webpage, I have various div elements displayed. Each div has the options to move it up or down using the buttons labeled "UP" and "Down". When a user selects a div, they can then use these buttons to adjust its position. I am looking for a way to au ...

Click the button to access the provided link

I need to add a link for redirection to some buttons. Here is an example of the button code: <Tooltip title="Open New Ticket"> <IconButton aria-label="filter list"> <AddTwoToneIcon /> </IconButton> </T ...

The React class component is throwing an unexpected error with the keyword 'this'

I encountered an error stating "Unexpected keyword 'this'" while attempting to update the React state using Redux saga. Could someone shed light on what's wrong with the code below and how I can fix it? class Welcome extends React.Component ...

In JavaScript, navigate to a new page only after successfully transmitting data to the server

Creating a redirect page that sends data to the server before transitioning to a new page can be achieved using JavaScript as shown below. <body> <script type="text/javascript"> **** Discussion of cookie-related transactions **** document.c ...

Automatically switch to the designated tab depending on the URL

Is it possible to automatically activate a specific tab based on the URL structure if my tabs are configured in this way? I am looking for a solution where a link on www.example1.com/notabs.html will redirect to www.example2.com/tabs.html This particular ...

Tips on creating a personalized memoizeOne function that delivers the accurate data type

I've implemented a function for object memoization: import memoizeOne from 'memoize-one'; type ArrayWithOneObj = [Record<string, unknown>]; const compareObject = ([obj1]: ArrayWithOneObj, [obj2]: ArrayWithOneObj) => obj1 === obj ...