Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do you dynamically create new object instances on the fly, using javascript?

I'm trying to create a new instance using a variable from an input field. I've been pushed in the direction of the 'eval()' method, and seeing this is client side code, I don't see this being a problem.

This is my code so far but it is just not working...

    function createPerson(name, gender, age) {      
        eval( "var " + name + " = new Person()" )
        eval( name + ".details('" + name + "', '" + gender + "', " + age + ")" )
    }

    createPerson('Liam', 'Male', 2)

Well, In the console, this does work, but my other functions in the file can't on it call it. I'm not sure if it would be, seeing the function is called at the same level as the below functions but, would this be scoping issue? 0_o

    $addAge.on('click', function() {
        Liam.increaseAge()
        Liam.displayHTML()
    })


    $minusAge.on('click', function() {
        if ( Liam.age <= 0) return;
        Liam.decreaseAge()
        Liam.displayHTML()
    })

The error I get from this is

     ReferenceError: Liam is not defined

But if I echo out to the console in the function that compiles the new instance, I can access the properties indivdually .

        console.log(Liam.name)
        console.log(Liam.gender)
        console.log(Liam.age)

returns

Liam script.js:58:3
Male script.js:59:3
2 script.js:60:3

Marcus Parsons. Any ideas man? I'm really stumped....

1 Answer

Hey Liam,

I'm not sure that I understand what you're trying to achieve but here is how I would create an object with those three values and function to add age. Hope that helps somehow :)

function Person(name, gender, age) {      
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

Person.prototype.addAge = function(age) {
    this.age += age
 }

var liam = new Person('Liam', 'Male', 2);

liam.addAge(2);

console.log(liam);

//outputs:  {name: "Liam", gender: "Male", age: 4}