1

I want to create a new instance of an object every time I click a button on my page. The problem is the reference variable, if you look at this example?

<input value="Create person" onclick="CreateObject()" />

......

function CreateObject(){
var person = new Person("Carl", 18);
}

Everytime the function is called an instance of the object is created, with the same reference variable. I want the reference variables to be different every time the function is called (eg. "person1", "person2", "person3"). What shall I do?

2
  • 3
    Create an array instead of giving in to Them and their blasphemous ways(tm)? Commented Nov 20, 2011 at 21:26
  • Even though the variable is the same, it is a new variable each time because the scope is different each time. After CreateObject returns, the person variable (and object) is discarded. Commented Nov 20, 2011 at 21:30

1 Answer 1

4

To use dynamic variable names (not recommended):

function CreateObject()
{
    window['person' + CreateObject.counter++] = new Person("Carl", 18);
}

CreateObject.counter = 0;

Better (as @delnan suggests) to use an array:

var people = [];

function CreateObject()
{
    var person = new Person("Carl", 18);
    people.push(person);
}
Sign up to request clarification or add additional context in comments.

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.