0
function Person(name) {

    Object.defineProperty(this, "name", {
        get: function () {
            return name;
        },
        set: function (newName) {
            name = newName;
        },
        enumerable: true,
        configurable: true
    });

    this.sayName = function () {
        console.log(this.name);
    };
}

var person1 = new Person("Nicholas");
var person2 = new Person("Greg");

console.log(person1.name);    // Nicholas
console.log(person2.name);    // Greg

person1.sayName();            // Outputs "Nicholas"
person2.sayName();            // Outputs "Greg"

How is that the accessor property name can use the named parameter name to store its value? Isn't a local variable garbage-collected after the execution of its containing context (in this case, the Person constructor)?

Enrique
  • 866
  • 2
  • 9
  • 20
  • 1
    What do you mean, you're explicitly creating a `name` property with `defineProperty`, why wouldn't it be available on the returned object, it's exactly the same as `this.name = name` ? – adeneo Mar 05 '15 at 17:18
  • @adeneo: OP doesn't ask why `.name` is available, but how the getter function can access the `name` variable. The answer of course is **closure**! – Bergi Mar 05 '15 at 17:22

0 Answers0