Challenges with Pushing Arrays to JavaScript Class Prototype

Upon clicking a button, I have the following script that triggers:

<button>Click</button>

<script>
  var test = function(){};
  test.prototype = {
    item:[]
  };

  $(document).ready(function(){
    $("button").on('click',function(){
      var t = new test();
      t.item.push(1);
      console.log(t.item);//[1],[1,1],[1,1,1]
    });
  })
  </script>

Could you explain why the value of t.item keeps looping instead of generating a new one without any previous values?

Answer №1

The reason for t.item being a reference to test.prototype.item is because new objects will inherit the item array.

To avoid this, you can create a new array on the object itself by using the following code:

var test = function(){this.item=[];};

This way, each instance will have its own unique array instead of sharing the same array from the prototype.

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

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

How to send a JSON Object and a CSV file using FormData

I need to send a JSON Object and a CSV file in a fetch request from my frontend to my backend. The JSON object is stored in the headerIngestion variable, while the CSV file is saved in the csv state. let formData = new FormData(); formData.append('h ...

Using Underscore.js to Group JSON Data in jQuery

I am looking to format my JSON data in order to create a chart for my daily reporting templates. The chart should display the number of Approved, Rejected, and Pending items on a daily basis. The current JSON data I have is as follows: json_data = '[ ...

What is the method for deactivating the voting button for a product review when the review's ID is present in local storage?

Managing reviews with user voting in a React app can be challenging. Each review can be deemed helpful or not, and each product may have multiple reviews. When a user votes on a review, the corresponding button should be disabled. I store the clicked revie ...

Switch out regex with an equal number of characters

I am looking for a way to replace specific content using a regex with the same number of characters but replacing them with a character of my choice. For instance: content: "abcdefghi*!?\"asd"; should be transformed into: content: "--------------- ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

An easy way to showcase Wikipedia's JSON data using JQuery

I would like to showcase the information found in the "extract" section of this JSON data retrieved from Wikipedia: { "query": { "normalized": [ { "from": "india", "to": "India" } ...

Get real-time input values

Struggling to retrieve input value in real-time? The goal is to dynamically update the bottom buttons. The first X should match the number of carrots specified in the input above, and the second X will be calculated by a script. The key is to ensure that ...

What about numerical inputs lacking spinners?

Is there a more efficient way for users to input a decimal number like 64.32, and have it be two-way-bound to a property of type number? I attempted to use <input type="number" [(ngModel)]="size"> However, this displays a spinner which isn't ...

Navigating to a different component with react-bootstrap-table-next?

I have a collection of coding challenges in a table format. I want the user to be able to click on a challenge name and be routed to a separate page showcasing the details of that specific problem using a Problem component with unique props. Currently, I ...

Can you pinpoint the issue with this asynchronous function in Vue3?

Dealing with a simple concept error, I find myself unable to solve it. Within the onMounted hook, everything looks correct - an Array of three objects is displayed. However, when I return it to the template and try to interpolate it, all I see is an empty ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...

Adding a method to a node module by hand

Working with my website, I've incorporated the material-ui package, but the version available on npm is outdated compared to the latest one on Github. To reflect these updates, I manually inserted this line of code into their Theme Manager class: set ...

I need help figuring out how to handle click events when using VueJS 2.0 in conjunction with a vue-mdl menu component

While @click doesn't seem to respond, v-bind:click does register. However, I'm facing the challenge of not being able to access the mdl-menu or mdl-menu-item components in order to add the method. The goal is to implement something like @click=" ...

Using express version 4.x to send an empty JSON object

I'm struggling with returning an object in JSON format using Express. What's confusing me is the following code snippet: class Greeting { Greeting(name) { this.name = name; } get name() { return name; } } app.get('/json/:na ...

AJAX brings back the previous value from an array

I am currently working on a website that will showcase various artwork. The concept involves using JavaScript to run a php file when the page loads, which in turn queries the server for the names and IDs of the image files (artwork.jpg) and displays them a ...

AngularJS's ScrollTo function allows users to scroll to a specific

Trying to implement a quick nav that smoothly scrolls to different sections on the page when a link is clicked. Currently using a guide provided by Treehouse for reference. $("#quickNav a").click(function(){ var quickNavId = $(this).attr("href"); ...

When using the JavaScript .sort() method, any undefined value must always be considered as coming before any other value

I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, wheth ...

Issue with THREE.SpriteCanvasMaterial functionality

This unique piece of code (inspired by this and this example): generateCircle = (ctx) -> position = 0.5 radius = 0.5 ctx.scale(0.05, -0.05) ctx.beginPath() ctx.arc(position, position, radius, 0, 2*Math.PI, fa ...

Custom AngularJS directive for ensuring the selection of a required HTML element

Today brings another question as I continue working on my web application. I've encountered an issue with the 'required' attribute not being widely supported in major browsers. The attribute only works if the first option value is empty, whi ...