1

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',
            success: 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.

3 Answers 3

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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.

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.