A JavaScript object retains past values even when moved to a new object

Objects in JavaScript can exhibit some strange behavior, which may not always be what you expect.

When I create a new Object() and set properties within it, I assume that each time I create a new instance, the object would have its default values. However, instead of this, I find that the properties set in the previous instance are retained. It's frustrating!

The following example clearly illustrates this problem:

function testo() {}

testo.prototype = {
  obj: {
    what: {
      value: 5
    }
  },
  done: function () {
    console.log(this.obj.what.value);
    this.obj.what = {value: 10};
  }
};

var x = new testo();
x.done();
var y = new testo();
y.done();

The output of the above code is:-

5
10

I had expected it to be:-

5
5

Why doesn't the output match my expectations? I thought that when creating a new instance of the Class() each object inside it should have its default properties without being affected by changes made in previous instances.

This example serves as a demonstration of the issue I am encountering in my library. I understand that it has to do with objects being stored as references.

How can I modify my approach to achieve the desired output? Any suggestions?

Answer №1

To increase efficiency, consider moving the prototype property to the 'this' object within the class.

function testo() {
    this.obj = { what: { value: 5 } };
}

testo.prototype = {
    done: function () {
        console.log(this.obj.what.value); this.obj.what = { value: 10 };
    }
};

var x = new testo();
x.done();

var y = new testo();
y.done();

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

Creating a mock AJAX response using JSFiddle and jQuery

Is there a way to simulate an ajax response in jsfiddle? The documentation at mentions using new Request.HTML, but it seems to only work with Mootools. When I tried using jQuery, I got an error saying "ReferenceError: Request is not defined". In the examp ...

Trouble with Setting a Background Image in Ionic with Javascript and Angular

I'm having trouble getting my background image to display in this Ionic project using CSS. It works when I embed it directly into the HTML, but that's not an ideal solution. I vaguely recall something about using base64 for images, but I'm n ...

Extracting multiple arrays from every record in a MongoDB collection

I've been struggling to find relevant information in Mongodb's documentation and despite trying numerous commands, I have yet to achieve the desired outcome. My mongodb database contains hundreds of documents, each with an array named "hashes" t ...

Setting default data in a data table that spans multiple pages is a useful feature that can

I am facing an issue with the default settings in the data table where I need the checkbox to be pre-checked on the controller's side. The problem arises when the checkbox is not staying checked after navigating to the second page and beyond. functi ...

Using Node JS as both an HTTP server and a TCP socket client simultaneously

Currently, I am developing a Node.js application to act as an HTTP server communicating with a TCP socket server. The code snippet for this setup is displayed below: var http = require('http'); var net = require('net'); var url = requi ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...

JQuery Tic Tac Toe Duel: Face Off Against Your Friend in a Thr

Looking for some advice here. I'm new to game development and currently working on a 2 Player Tic Tac Toe game. I need help with implementing the game functionality. Any suggestions? I want to disable the "div" once a player clicks on it, but I' ...

Issue with event binding on datepicker that is dynamically added is not functional

I have integrated the Kendo datepicker into my project, and I am facing an issue with duplicated div elements containing datepickers. The problem is that the datepicker events only fire once on the first duplicated div and then stop working altogether. I ...

Tips for inserting a jQuery snippet into a universal file

Seeking some advice on integrating jQuery code into my JavaScript file, which is located at . The code snippet I am attempting to add looks like this: $(document).ready(function() { queue = new Object; queue.login = false; var $dialog = $ ...

`Is it possible to determine when a Scroll event has completed using jQuery?`

Similar Question: Javascript: trigger function after user finishes scrolling Is the Scroll event triggered as soon as the user starts scrolling the page? How can I determine when the user has finished scrolling so that I can execute a function afterwa ...

The contents of an Array sourced from a SharedArrayBuffer will consistently be comprised of zeroes

Regardless of my efforts, whenever I create an array from a buffer (no need for sharing), the resulting array contains elements equal to the length of the buffer, with all values being zero. It seems like the documentation on typed arrays in Mozilla doesn& ...

Storing items in a pre-save hook using Mongoose

I have files that I need to generate, but these files include links, so the structure of the file looks like this: const file = { name: 'some name', content: 'some content, type: 'file type', links: [{ path: 'some ...

Creating a 3D rectangle using three.js with box2d rectangle rendering

When it comes to rendering box2d bodies on the canvas, a common issue arises. Box2d provides us with the center of the body and its angle, while the canvas draws shapes like rectangles from the top-left corner. I encountered this problem but managed to fin ...

Using CSS to select multiple nth-child elements in a single rule is

If we take the following css code: div div p:nth-child(1), div div p:nth-child(2), div div p:nth-child(3), div div p:nth-child(4), div div p:nth-child(5) { } This will target elements with nth-child from 1 to 5. Now, let's lo ...

The custom context provider is unable to output any content, even basic HTML elements

I came across this tutorial that guides on implementing a custom AuthContext provider in React. The suggested code snippet provided is as follows: const AuthProvider = ({ children }) => { const [token, setToken] = React.useState(null); const handle ...

Is there a way to locate and refine the blogs associated with a specific user?

Check out the following blog entries stored in the Database: [ { _id: 5fec92292bbb2c32acc0093c, title: 'Boxing ring', author: 'T. Wally', content: 'boxing stuff', likes: 0, user: { _id: 5fd90181 ...

Retrieving information from MongoDB in an Express.js route handler

I'm trying to create a validation function that can check for the existence of a mongo_id. I've managed to write the function, but I'm struggling to pass the result back to the calling route. Below is the code for the function, based on an ...

Appears as though time is slipping away during date conversions

I seem to be experiencing a strange issue where I lose a day when transitioning between MySQL and my JavaScript code, and I can't seem to figure out why. When I insert a date into the database (for example, 10/14/12), it appears as 10/13/12 in the dat ...

Why is FileList.item giving me an error?

Why am I getting an error saying the item property of a FileList variable is not a function? To clarify, I retrieve all files from a file input and store them in an array as type FileList successfully: files: any = []; onImageSelect(files: any = FileList ...

Storing various two-dimensional arrays in Python can increase efficiency and organization

How can I efficiently store multiple numpy arrays with varying dimensions? For example, I have 5 numpy arrays of size 100x1, 4 arrays of size 100x3, 3 arrays of size 100x5, and 4 arrays of size 100x6. Storing each in separate numpy arrays may not be effi ...