Ben_hawk
Ben_hawk

Reputation: 2486

JavaScript initialise function

If I created a javascript object like so:

Test = function(params) {
    this.test = params.test || 'element';
    this.test1 = params.test1 || '#000';
    this.test2 = params.test2;
    this.test3 = params.test3;

    //need a neat little initialise function to create some html elements here! 
}

var test = new Test({test: "#CCC", test1: [0, 1, 3], test2: [0, 1, 3]});

How would I then create a proper initialise function that would run when an instance of that object was created like above.

Would I simple make a function and then call it, or is there a way to make a function that runs on its own when an object instance is created.

Upvotes: 0

Views: 508

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

You already have an initialise function, that's where the variables are being defined. Just do stuff there, and it will happen when you create an instance of the object.

Upvotes: 1

Bergi
Bergi

Reputation: 664936

Your constructor already is a function, you can just place the code there. Technically speaking, the constructor is the initialisation function for objects.

Would I simple make a function and then call it, or is there a way to make a function that runs on its own when an object instance is created.

That depends. Can you reuse the html element creation code somewhere else than in the constructor? Then put it in a separate function (possibly on the prototype) and call that from the constructor.

Upvotes: 3

Related Questions