I’m having a lot of trouble with my javascript page.
Basically, I have a html/javascript page that gets data from a php page. I’m doing this multiple times, pushing them into the array, and then displaying the array.
Here’s a rundown of the code
var spawnedNewspaper = [];
var articlesToSpawn = null;
$("#generate").click(function() {
spawnNewspaper();
});
function spawnNewspaper(){
if(itemsToSpawn==null){
articlesToSpawn = 4;
spawnedNewspaper = [];
}
if(itemsToSpawn > spawnedNewspaper.length)
spawnAnItem();
if(itemsToSpawn == spawnedNewspaper.length){
itemsToSpawn = null;
// ... display the results
}
}
function spawnAnItem(nationalDexID, level, generateRandomBerry, generateRandomTMItem, generateRandomItem, knowsRandomTM, imageURL){
$.getJSON("...url.../spawner_json.php?jsoncallback=?" ,
{
dataitename: data
}
, spawnAnArticlePart2
);
}
function spawnAnArticlePart2(data){
//returning from spawnAnItem callback
p = ArticleObject(data.heading, data.date, data.author)
spawnedNewspaper.push(p);
spawnNewspaper();
}
function ArticleObject(heading, date, author){
this.heading = heading;
this.date = date;
this.author = author;
return this;
}
So, after it’s done, it shows my array with the correct number of articles, but each article is exactly the same when I know that it’s generating unique things each time.
My thoughts are that there’s a concurrency problem and things are being overwritten (I used push() so this is odd), or that there’s a problem with my ArticleObject.
Any ideas on how to fix this?
Change this line:
To use the
newoperator:And then within your
ArticleObject()function you don’t need to sayreturn this;becausethiswill be returned automatically when the function is called withnew.What’s happening is when you call the function with
newJavaScript creates a new object that inherits fromArticleObject.prototypeand within the functionthispoints to that new instance. When you call the function withoutnewJavaScript is settingthistowindowso each time your function runs it just updates the same properties onwindow.For more information about using
newread what MDN has to say about it.