Javascript - Array of 'classes'
I'm trying to create an array of 'classes' like so:
function Main(initURL){
var item_array = [];
this.initURL = initURL;
function construct() {
$.ajax({
url: initURL,
dataType: 'json',
suc开发者_如何学编程cess: function(data){
for(var i=0;i<data.length;i++){
var item = new Item(data[i]);
item_array.push(item);
}
init();
}
});
}
function init() {
setInterval(update, 1000);
}
function update() {
for(var item in item_array){
console.log(item.name);
}
}
construct();
}
function Item(data) {
var dirty = false;
function init(data) {
this.id = data.pk;
this.name = data.fields.name;
}
init(data);
}
When attempting to print out the item name, I'm getting "undefined". Is there more to it than this? Data.field.name is definitely set.
A for..in
loop loops through keys, not values. Change it to:
for(var i = 0; i < item_array.length; i++) {
console.log(item_array[i].name);
}
Don't use for... in
to iterate over an array.
for(var i=0; i < item_array.length; i++){
console.log(item_array[i].name);
}
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in#Description
The problem is that you're calling your "init()" function in "Item()" without any context object. Thus, this
isn't the object you want it to be. Try this change:
function Item(data) {
var item = this;
function init(data) {
item.id = data.pk;
item.name = data.fields.name;
}
init(data);
}
Now, I'm not sure why you'd want to write the function that way in the first place; that little "init()" function doesn't really do anything useful. It could just be:
function Item(data) {
this.id = data.pk;
this.name = data.fields.name;
}
and that would work too.
精彩评论