Josh Lyness Josh Lyness -3 years ago 130
Javascript Question

Javascript - make array of objects and understanding constructors

I know this question has been asked before, but they're always project specific and I can't find what i'm looking for.

I need an array of objects in javascript. I have declared a class as :

var svgData = {.....}

(the keyword class isn't available in esversion: 5)
and I have an array variable :

var svgContent = [];

I tried doing it like you would in C# where you would write :

svgContent[0] = new svgData();

However you would normally create a constructor for it, which as far as I can tell, doesn't exist in javascript. I have been using a function like this:

function SvgData (....) {
this.var = ...;

but the problem is that there is no link between this and the class, and as such I have an issue that when I try to access a variable in the array using a for loop like this:

for(var i = 0; i < length; i ++){

it returns the same number repeatedly (its just overriding itself, since the way i have done it has linked every array element to the exact same variable svgData{}.
How do I make an instance of a class (object)? And how do you link the constructor to the variable?

Answer Source

You should consider the fact the JavaScript is a standalone language and implement things in its own way. From your question, I understand you want an array (which is still an object in JS, just with some special properties) of objects and you want those object to be made from a template (let's say a "class").

You've mentioned that there are no constructors, since there are no classes. But the way you've used function SvgData is exactly how you can design "classes". That's called a constructor function and it's special because it has no other statements than assignments to this object and thus it implicitly returns the this object (a constructor function is any function which returns the this object).

The syntax: new SvgData is basically syntax sugar for: create a new empty object (from "new") and assign to it the this object that is returned from whatever function comes next.

function SvgData (val) {
    this.var = val;

var myLength = 10;
var myArr = [];

for (var i = 0; i < myLength; i ++) {
    myArr.push(new SvgData(i));


This should do what you want it to do. You can test it here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download