yaron
yaron

Reputation: 1333

javascript - how to get object from array, and use its methods?

i have a problem using a class methods, after it was inserted into array. when i pull it back i can no longer use it methods.

suppose i have the following:

// a simple atomic class

function raw_msg(msg) {
  this.msg = msg;

  this.print = function () {
    console.log(this.msg);
  }

}

 // and then i have this container for this "atomic" class
 // which accept array of unknown object (known to me though..) = in_buffer
 // i.e in_buffer is just an array of objects (one type of object)

function buffer(in_buffer) {

  this.trans_buffer = null;

  if (in_buffer!=null)
     this.set_buffer (in_buffer);

  this.set_buffer = function (buffer) {
    this.trans_buffer = [];
    var length = buffer.length,
      row, new_raw_msg;
    for(var x = 0; x < length; x++) {
      row = buffer[x];
      this.trans_buffer.push(new raw_msg(row));
    }
    console.log(this.trans_buffer);
  }

  this.use_some_raw_msg_method = function () {
    var firstrow = this.trans_buffer[0];
    firstrow.print(); // here is the problem!!!
    //this here where i need help as it yield the error:
    //Uncaught TypeError: Object #<Object> has no method 'print' 
  }
}


// this is how i use it, this code sits in a diffrent yet another class...

// this here im just building fake array
var buffer_in = [];
for (var x=0;x<10;x++)
   buffer_in.push ("whatever" + x);

this.trans_buffer = new trans_helper(buffer_in);

this.trans_buffer.use_some_raw_msg_method (); // will yield the error as described

i hope this here, is clear, ask away if you need clarifications.

thanks for your help!

Upvotes: 0

Views: 140

Answers (1)

Shadow Wizard
Shadow Wizard

Reputation: 66389

You had several problems with your code.

  1. Associative array does not have .push() method so the following line failed:

    buffer_in.push ("whatever" + x);
    

    To fix this just declare plain array:

    var buffer_in = [];
    
  2. You tried to create instance of function called trans_helper which does not exist. The name is buffer instead, so fix would be:

    var trans_buffer = new buffer(buffer_in);
    
  3. Last but not least, you tried to call function in the "class" when it still did not exist yet. JavaScript does not "compile" functions in advance, when inside function it will go line by line. So in this line in your code:

    this.set_buffer (in_buffer);
    

    There was still no function called "set_buffer" in your class. To fix this, place the function declaration above, on top.

Live test case.

Upvotes: 1

Related Questions