What causes cloned object methods to become corrupted when using .clone()?

I found a simple solution, but I'm intrigued. I'm not totally clear on the inner workings of .clone().

To standardize vectors, I created this class:

class Vector {
  constructor(x,y){
    this.x = x
    this.y = y
  }
  normalize() {
    let length = Math.sqrt(this.x * this.x + this.y * this.y)
      this.x = this.x / length
      this.y = this.y / length
  }
}

After importing a GLTF model (excerpt from code):

const loader = new GLTFLoader();
loader.load( './assets/models/ROCKS.glb', function ( glb ) {

glb.scene.userData.mouseDirVector = new Vector(0,0)

obj = glb.scene
obj2 = obj.clone()
}

Upon trying to use the .normalize() method on the Vector object in later code, an error arises (specifically with the cloned object):

Uncaught TypeError: obj2.userData.mouseDirVector.normalize is not a function

What could be causing this issue?

Answer №1

According to the documentation, when using .clone(), function references are not preserved during object cloning.

Please note: as pointed out by DonMcCurdy, the method below will not work because the object does not have a prototype

You can attempt to include the method within the UserData prototype itself:

UserData.prototype.mouseDirVector = new Vector(0, 0);

This way, the method will be accessible in all subsequent instances of UserData without needing to redefine it. In this scenario, this refers to your specific object, not the Tree object.

Alternatively, you can reassign the property:

obj2 = obj.clone();
obj2.userData.mouseDirVector = new Vector(0,0);

Answer №2

As far as I know, there is not a single clone() method specifically for cloning objects. It would be more appropriate to utilize the structuredClone(), JSON.parse/stringify approach, or any library for object cloning. For further information, you can visit deep clone object in JavaScript.

In terms of the clone() method mentioned, it seems like you may be referring to either Response.clone() or Request.clone(). It is recommended to identify the specific method being used and refer to the respective documentation. Alternatively, feel free to return here with detailed information about the method in question.

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

Show detailed information in a pop-up window

Javascript $(function() { var dmJSON = "clues.json"; $.getJSON( dmJSON, function(data) { var idx=1; $.each(data.details, function(i, f) { var myid = 'mypop'+String(idx); idx++; var $popup="<popu ...

When the span tag is inserted into a contenteditable element on iOS Safari, the cursor automatically shifts to the

One interesting feature allows users to click on a tag and have it added to a contenteditable div. This function works smoothly initially, but when toggling back and forth, the cursor unexpectedly jumps to the end of the div. When a user adds a variable f ...

Making a <canvas> Element Bigger

I've encountered an issue with resizing my canvas using the width and height attributes. Despite adjusting these values in my code, the canvas remains the same size. Here's the snippet of the code: <!DOCTYPE HTML> <html> <head ...

Is it possible for Javascript to "target" divs through Ajax requests?

I am facing a challenge with my main program that includes multiple Javascript routines, one of which involves Ajax. The issue I am encountering is related to modifying the attributes of returned html elements within the calling page using another Javascri ...

Tips for converting a select option into a button

Currently, I am working with Laravel to develop my shopping cart. My goal is to implement a feature that allows customers to select the quantity of a product and have the price update accordingly when they click on a specific number. However, I am facing a ...

Utilizing JavaScript to trigger a series of click events on a single button in order to

I am working on implementing a click event for a checkbox that will add and remove CSS classes using the "classList.toggle" method. Specifically, I want the checkbox to toggle between adding the "xyz" class on the first click, and then adding the "abc" cla ...

Encountered a 404 error while attempting to build and serve a Vue.js project using 'npm build' in Apache Tomcat

After setting up a Vue.js project, the configuration in the package.json file looks like this: "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": ...

Alter the button's color seamlessly while staying on the same page

I have implemented a feature that allows me to change the category of photos without having to leave the page and it works perfectly. My next goal is to create a button system where the pre-defined category of a photo is indicated by a button with a green ...

Discovering the expected parameters of a function

My function looks like this: function myFunction(params) { // TODO: something console.log(params.message) } I want to find out all the keys that the 'myFunction' function expects in the params object. Can this be done? I attempted to use ht ...

Is there a way to create a JavaScript function that relies on a successful form submission?

After attempting to modify a post on Stack Overflow, I am facing issues with my JavaScript code. As a beginner, it's possible that I overlooked something in the code causing it not to work as expected. The project I'm working on involves creatin ...

When Typescript compiles to JavaScript, it may result in code that appears to be a function

In the following typescript code snippet: export enum UID { FACTORY, ROBOT } we see how it compiles to javascript: (function (UID) { UID._map = []; UID._map[0] = "FACTORY"; UID.FACTORY = 0; UID._map[1] = "ROBOT" ...

Rendering Radial Gradients Using CSS3 in Google Chrome

While experimenting with animating radial gradients using jQuery, I came across an interesting observation (take a look at this JSFiddle). As I moved the mouse pointer over the left side of the element, the position animation appeared smooth. However, movi ...

Flatbuffers does not exist in this context

Currently, I am working on a nodeJs application that involves the use of Google Flat Buffer. After installing flatc on my MacBook Pro, I compiled the schema below: namespace MyAlcoholist; table Drink { drink_type_name: string; drink_company_name: stri ...

Discovering if a subdomain is present using Python

Is there a way to verify the existence of a subdomain on a website? I am currently working on a sign-up form where each user receives their own subdomain. While I have implemented some JavaScript on the front end, I now need a method to validate this on t ...

Troubleshooting Appium error management is ineffective

As a newcomer to appium, I might have made some mistakes. I'm encountering a problem with appium while using wdio and jasmine. it('wtf', (done) => { client.init().element('someName').getText() // ^ here ...

Running multiple npm scripts on both Unix and Windows systems can be achieved by using the "npm

Is there a way for me to execute multiple npm scripts synchronously, one after another? Below are the npm scripts I have in my project, which includes both bower and npm packages: { "scripts": { "installnpm": "npm i", "installbower": "bower i", ...

SyntaxError: The input on line one ended unexpectedly and was not caught

This issue is commonly associated with messy close parentheses, however, the error is occurring on line 1 of the file! Below is the javascript code from (filename: calculate.js) var colors = new Array(); colors["SILVER"] = -2; ... Although there is m ...

Failed attempt to perform Ajax requests for REST API data

I am currently working on developing an application that requires a login through a REST API to retrieve a session id. To achieve this, I have set up a button that triggers a JavaScript function for making an AJAX call to authenticate the user. The result ...

What could be causing the 500 error when receiving images from the API, while all other data is successfully retrieved?

I've encountered a puzzling issue while running my Next.js project. When requesting a photo from the API, I receive a 500 error, whereas other data like price is fetched without any problem. Below is the fetchApi snippet: import axios from "axio ...

determine the color of the pixel at the top left corner of a jpg image

If we were given a specific URL, for instance, "//upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg", how can we use javascript (specifically jQuery or Angular) to obtain the top left coordinates (or any (x,y) coordinates) of this image? Just to clarify, ...