petehallw
petehallw

Reputation: 1014

Alter properties of objects in a function (Javascript)

I have declared a variable in my main html page as such:

var ColorBuffer;

I pass this variable into a function:

myFunc("example.txt", ColorBuffer);

Within this function a property of the variable is set as shown:

function myFunc(file, colBuf)
{
    ...

    colBuf.items = 4;
}

However when I refer to 'ColorBuffer.items' within my main html page I get the error 'Cannot read property 'items' of undefined'.

So it seems that using the parameter name colBuf does not affect the argument ColorBuffer passed in...how could I set the items property of ColorBuffer from within my function?

Many thanks.

Upvotes: 0

Views: 41

Answers (2)

Brennan
Brennan

Reputation: 5732

The variable is undefined because it has no value. What will the variable be, an array? String? Plain Object?

Whatever it may be, give it a basic value:

var ColorBuffer = {}; //For object
var ColorBuffer = 0; //For number
var ColorBuffer = []; //For array
//etc etc

Upvotes: 0

elzi
elzi

Reputation: 5672

Setting ColorBuffer as an object will resolve this.

var ColorBuffer = {};

Upvotes: 1

Related Questions