Danny
Danny

Reputation: 9614

how to create an object's array in javascript

I recently encountered an problem where I am not creating an array correctly for objects.

So I tried to do the following thing in javascript:

function Mesh()
{
    this.buffer = [10, 10, 10];
}

Mesh.prototype.getBuffer = function ()
{
    return this.buffer;
};

function main()
{
    var model = new Mesh();
    var modelBuffer = model.getBuffer;
    document.getElementById("textSection").innerHTML = modelBuffer[0];
}

I'm trying to avoid using global variable hence I've created the array the way I did in my Mesh() constructor. But when I try to retrieve the data from slot 0 it prints "undefined". How do I get this work? I really have no idea why this is happening...

Upvotes: 0

Views: 51

Answers (1)

Cerbrus
Cerbrus

Reputation: 72857

Try:

var modelBuffer = model.getBuffer();

Instead of:

var modelBuffer = model.getBuffer;

You were assigning the function to the variable, instead of calling the function.

It's always a good idea to console.log() variables that don't return what you expect them to. In this case:

console.log(modelBuffer);

Logged:

// function ()
// {
//     return this.buffer;
// }

Pointing me into the direction of the modelBuffer assignment, for example.

Upvotes: 3

Related Questions