Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Arrays as an object field

I am running into a problem with using an array as a Javascript field.

var Object = function () {

  var admins = [];

  this.addAdmin = function(admin){
    this.admins.push(admin)
  }

}

Normally I would expect admin to be pushed into the array admins but instead I get a ‘cannot read property ‘push’ of undefined’.

If I’m not mistaken when I initialized the Object with new Object(), admins = []; should initialize the array. Is this a limitation of Javascript?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance.

>Solution :

var array creates a local variable. It does not create a property on the object.

You need:

this.admins = [];

or

admins.push(admin) /* without this */
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading