When arrays are recalled, access to functions is lost for Javascript object instances

Check out this code snippet I have:

var cobj = {
  a: 0,
  b: 0,
  c: 0,
  asdinit: function(x, y, w, h) {
    this.a = x;
    this.b = y;
    this.c = w;
    this.h = h;
  },
  adsfads: function(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

var c = new cobj.asdinit(1, 1, 1, 1);
var bigarray = []
for (t = 0; t < 10; t++) {
  var newobj = new cobj.asdinit(1, 1, 1, 1);
  bigarray.push(newobj);
}
for (t = 0; t < 10; t++) {
  var localobj = bigarray[t];
  localobj.adsfads(1, 1, 1, 1);
}

Upon object creation, all functions are accessible. However, after being retrieved from the array, the functions seem to be no longer available. Why is that?

Answer №1

To improve your code, consider restructuring it so that a function is responsible for returning objects.

var objectCreator = function() {
  return {
    a: 0,
    b: 0,
    c: 0,
    initialize: function(x, y, w, h) {
      this.a = x;
      this.b = y;
      this.c = w;
      this.h = h;
    },
    updateValues: function(a, b, c, d) {
      this.a = a;
      this.b = b;
      this.c = c;
    }
  }
}.bind(this)

var objectInstance = objectCreator();
var c = objectInstance.initialize(1, 1, 1, 1);
var array = []
for (t = 0; t < 10; t++) {
  var newObj = new objectInstance.initialize(1, 1, 1, 1);
  array.push(newObj);
}
for (t = 0; t < 10; t++) {
  var localObject = array[t];
  localObject.updateValues(1, 1, 1, 1);
}

Answer №2

Utilizing the asdinit and adsfads functions as constructors results in objects with only a, b, and c properties, lacking prototype methods.

An alternative approach could be:

class cobj {
  constructor (x, y, w, h) {
    this.a = x
    this.b = y
    this.c = w
    this.h = h
  }
  
  adsfads (a, b, c, d) {
    this.a = a
    this.b = b
    this.c = c
  }
}

var bigarray = []
for (t = 0; t < 2; t++) {
  var newobj = new cobj(t, t, t, t);
  bigarray.push(newobj);
}
for (t = 0; t < 2; t++) {
  var localobj = bigarray[t];
  localobj.adsfads(t + 1, t + 1, t + 1, t + 1);
  console.log(localobj)
}

For more information, refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes


In ES5, the equivalent would be:

function cobj(x, y, w, h) {
  this.a = x
  this.b = y
  this.c = w
  this.h = h
}

cobj.prototype.adsfads = function(a, b, c, d) {
  this.a = a
  this.b = b
  this.c = c
}

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

How to retrieve the latest document from every sender within a JavaScript array using Mongoose/MongoDB queries

I recently created a schema: var messageSchema = mongoose.Schema({ sender:String, recipient:String, content:String, messageType: Number, timestamp: {type: Date, default: Date.now} }); Next, I defined a model for this schema: var Mess ...

ExtJS web displays appear differently when viewed on Chrome's toggle device mode versus a mobile browser

Greetings, I have been working on developing a web application that can be accessed through a mobile browser. Initially, I created the web application and tested it in mobile mode using Chrome's simulation feature. https://i.sstatic.net/aAvVW.jpg H ...

Unable to retrieve data from SpringBoot controller using $http.get request

I have developed an application that will execute queries on my store's database based on user input on the webpage. The backend method is functioning correctly and returns the response, but I am having trouble displaying the data in a dynamic table o ...

Error: Unable to locate module 'child_process' in the context of NextJS + Nightmare

Encountering an issue while trying to compile a basic example using Next JS + Nightmare Scraper. Upon attempting to access the page, I am faced with the following error message, and the page fails to load. PS C:\Users\lucas\Documents\Pr ...

What is the best way to add new input fields dynamically using the push() function in AngularJS?

I'm currently working on implementing an add more field feature in angularjs. Here is the code that I am using: Javascript <script> function FruitsController($scope){ var div = 'Apple'; $scope.fruits= ...

Calculating the mean of elements in 3D arrays using Numpy element-wise operations

Need to calculate the average of 9 arrays element-wise to consolidate into one. Searching for a quick solution as the initial code is extremely slow. Using NumPy mean function without specifying an axis results in a single value, but I require the mean el ...

Is there a way to access the value of an IPC message beyond just using console log?

I am developing an app using electron and angular where I need to send locally stored information from my computer. I have successfully managed to send a message from the electron side to the angular side at the right time. However, I am facing issues acce ...

Switch from using fetch to utilizing axios for making API requests

I used fetch for a 'get' request, but now I want to switch to axios. Can someone please help me convert this code to use axios instead? More details: I am fetching an image and using the blob method to display it to the user. I would like to ach ...

Enhancing functionality with jQuery: updating multiple input fields at

Currently, I am attempting to utilize jQuery to modify some HTML text by adjusting a slider. I have managed to accomplish this; however, I also need it to happen only if a checkbox is checked. How can I integrate both conditions and ensure that the text ch ...

Is the object returned by the useParams hook maintained across renders?

The book that is displayed is based on the URL parameter obtained from the useParams hook. The selected book remains constant across renders unless there is a change in the value returned by the useParams hook. I am curious to find out if the object retur ...

What is the best way to transfer information from JavaScript to a JSON database using the fetch API?

Within the userDB.json file, it appears as follows; [{ "username": "john", "xp": 5 }, { "username": "jane", "xp": 0 } ] Inside the app.js file ; async function getUsers() { le ...

Encountering Syntax Error while running `ionic serve` in IONIC2

I'm stuck on this Syntax error and I can't figure out what went wrong. It keeps showing up even though I copied the code directly from the official ionic2 docs. SyntaxError: D:/Manson/Arts/Ionic/IonicTodo2/app/pages/list/list.js: Unexpected toke ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...

AngularJS directive that offers dynamic functionality

Currently, I am working on dynamically inserting an ng-options directive within various <select> elements throughout my application. These elements have their own unique class names and other directives, such as ng-if, among others. <div ng-app=" ...

Executing an external JavaScript function from within an internal JavaScript code block

Currently, I am dealing with 2 JavaScript blocks. One is contained within my HTML and handles touch functionality, while the other is an external file serving as a content slider. My goal is to utilize touch events to control the slider - allowing users to ...

What is the best way to delay JavaScript execution until after React has finished rendering?

Perhaps this is not the exact question you were expecting, but it did catch your attention :) The issue at hand revolves around the fact that most of the translations in my text do not update when the global language changes. Specifically, the translation ...

Struggling with setting up a PHP and Ajax registration and login system

Struggling with my code and in need of assistance. Desperately trying to set up a register form where users can input their username and password to sign up. Planning to utilize ajax, however, the integration seems faulty. For testing purposes, I tried ech ...

Is there a way to verify the authenticity of a survey depending on the types of form elements used

Creating a form in PHP with various dynamic form elements like radio buttons, text fields, and dropdowns. Seeking to validate this form using JQuery based on the question type, which is identified by the names q1, q2, etc. $(function(){ if ($(&apo ...

Validating date parameter in Wiremock request - How to ensure dynamic date matching during testing?

Looking for some assistance in verifying that the date in a request is exactly Today. I've tried various methods from the documentation, but haven't achieved the desired outcome yet. Calling out to any helpful souls who can guide a junior QA thro ...

Ways to implement the tabIndex attribute in JSX

As per the guidelines provided in the react documentation, this code snippet is expected to function properly. <div tabIndex="0"></div> However, upon testing it myself, I encountered an issue where the input was not working as intended and ...