2

I am trying to create a list of objects that are listed in an array. newConstant is a function that creates the objects and them pushes them to the array. However, when the while loop runs through the array and throws up alerts containing one of the properties of each array, it spits out the value for the last object for each object in the array. In this situation it alerts "3" each time, but it should alert "1", then "3", as those are the value of the property x for the two objects in the array "a". The code is below. How can I fix this?

var i = 0;
var a = [];
var newConstant = function (x, y) {
    this.x = x;
    this.y = y;
    a.push(this);
};
var one = newConstant(1, 2);
var two = newConstant(3, 4);

while (i < a.length) {
    alert(a[i].x);
    i++;
}
2
  • 1
    every object in the array is window. Commented Feb 6, 2013 at 23:44
  • @zzzzBov I address that in my answer :) Commented Feb 7, 2013 at 0:11

2 Answers 2

1

You're written newConstructor as a constructor but you're using it as a normal function, try adding the new keyword.

var i = 0;
var a = [];
var newConstant = function (x, y) {
    this.x = x;
    this.y = y;
    a.push(this);
};
var one = new newConstant(1, 2); //notice the new keyword indicating a constructor
var two = new newConstant(3, 4);

while (i < a.length) {
    alert(a[i].x);
    i++;
}

Here it is in action: http://jsfiddle.net/V3zwW/

Here is an article about the this keyword in javascript. Here is another reference on how to correctly use the Constructor pattern

What happened before is that your second call set this.x to 3 However this referred to the window , this is because functions in javascript assign this to their caller unless they are constructors. In your case you alerted window.x (which you set to 3) two times resulting in 3 3

Sign up to request clarification or add additional context in comments.

Comments

0

you have forgotten about the keyword "new", see the example below:

var one = new newConstant(1, 2);
var two = new newConstant(3, 4);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.