简体   繁体   中英

Javascript: All Objects in Array Have Same Properties

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++;
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM