lundi 2 mai 2016

Beginner JavaScript Pattern

I'm recently started studying objects, closures, scopes and the such. I'm trying to implement my own code using these techniques but am running into issues.

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

    return {
        ageUp: function ageUp() {
            this.age++;
        },
        printInfo: function printInfo() {
            console.log(this.name + " is " + this.age + " years old");
        },
        changeName: function changeName(newName) {
            this.name = newName;
        }
    }
}


var jeff = new Person('jeff', 28);
jeff.printInfo();

Oddly, this returns undefined is undefined years old. Does the printInfo property not have this.name in it's scope because the returned object has no recollection of the function?

Also oddly enough, if I change all the instances of this.name and this.age to regular private variables (such as var personName = name;), somehow the returned object will operate properly and I can use the ageUp and printInfo as expected.

Am I combining two design patterns that I shouldn't be? What would be the best way to go about this?

Aucun commentaire:

Enregistrer un commentaire