dublintech
dublintech

Reputation: 17785

Is this a javascript closure?

I have this....

function MyFunction() {
    var myVar = "I think I am encapsulated";

    this.getMyVar = function() {
        return myVar;
    }
}

var myProperty = new MyFunction();
console.log(myProperty.getMyVar());

myProperty.myVar = "you're not encapsulated";
console.log(myProperty.getMyVar());

It outputs: "I think I am encapsulated twice". Why? I did not think this was a closure...

Upvotes: 1

Views: 200

Answers (3)

Brendan Long
Brendan Long

Reputation: 54242

var myVar = "I think I am encapsulated";

this.getMyVar = function() {
    return myVar;
}

This is a closure, and the myVar variable from the time the function was created will be returned. Notice that's it a local variable, so there's no other way to access it after this function exits.

var myVar = "I think I am encapsulated";

Notice that this is not this.myVar (the variable you're setting later with myProperty.myVar).

Probably what you're trying to do is:

function MyFunction() {
    this.myVar = "I think I am encapsulated";

    this.getMyVar = function() {
        return this.myVar;
    }
}

Upvotes: 2

Alex
Alex

Reputation: 35409

Yes, it is.

When you define a function inside of another function, the inner function has access to all of the outer function's local variables...

In your case, getMyVar has access to myVar - through the closure.

Upvotes: 2

Pointy
Pointy

Reputation: 413727

The closure is around the "getMyVar" function. The variable "myVar" inside the constructor is a local variable, and not visible outside the function except as the return value from "getMyVar".

Setting a "myVar" property on the object does just that, but the "getMyVar" function is not returning a property of an object; it's returning the value of the local variable in the closure.

Upvotes: 6

Related Questions