Search code examples
javascriptclosuresencapsulation

If a variable is enclosed, and an instance sets a property with the same name, where does the property go?


Most of us know that JavaScript has no sense of "private" properties, but that behavior can be emulated through the use of closures:

var Car = function () {
    var name = 'Tesla';
    var wheelCount = 4;

    this.getName = function () {
        return name;
    };
    this.getWheelCount = function () {
        return wheelCount;
    };
    this.setName = function (newName) {
        name = newName;
    };
    this.setWheelCount = function (newCount) {
        wheelCount = newCount;
    };
};

var myCar = new Car();
console.log(myCar.name); // undefined

That all makes sense to us that know about how JavaScript closures work. However, the following will work:

myCar.name = 'Corvette';
console.log(myCar.name); // 'Corvette'

But then if you call the function from the prototype, the enclosed variable is still used

console.log(myCar.getName()); // 'Tesla'

When you call myCar.name, you're adding a new property to the object. Is it just the entire point of using this when declaring the getName (etc) functions inside the Car definition to make the differentiation between the enclosed name inside the Car declaration versus the myCar.name?

I have a feeling that I know the answer to this, but I would like to be certain. Plus, I think this would be something invaluable to other people getting an advanced grasp on how JavaScript enclosures work.


Solution

  • Is it just the entire point of using this when declaring the getName (etc) functions inside the Car definition to make the differentiation between the enclosed name inside the Car declaration versus the myCar.name?

    Yes.

    this (or myCar) is the object, on which you put the properties that you want to have it (in this case all those methods). If you want to use properties, you must use a property accessor.

    var name is just a local variable in the constructor function, which is accessed by closure from the object's methods.

    Or, to answer your title question:

    If a variable is enclosed, and an instance sets a property with the same name, where does the property go?

    The property goes on the object. It doesn't interfere at all with the variable, which is located in the scope of the Car constructor invocation.