Frage

Consider this trivial code I tried in Chrome's console:

function Container() {
    var secret = 3;
    this.getSecret = function() {
        return secret;
    }
}

Now, I cannot retrieve 3 by executing:

var c1 = new Container();
c1.secret //yields undefined

However, this works as expected

c1.getSecret() //returns 3

Now, this is the quirky thing I tried:

c1.secret = 10;
c1.getSecret(); //I was expecting it to return 10

However, it returns 3. When I see the object in the console, it looks like this:

Container {getSecret: function, secret: 10}

Can someone explain why c1.secret = 10 didn't change the value of the secret private variable in the object? Are there two fields with the name "secret"?

I'm confused what the final object really looks like in memory.

War es hilfreich?

Lösung

private is a really confusing word.

The secret var you declared using var secret = 3; is not a 'private' variable. This is a variable that is only visible in the Container constructor scope. And because you declare the method getSecret in the same scope, it has access to it.

if you had done:

function Container() {
    var secret = 3;
}

Container.prototype.getSecret = function() {
    return secret;
}

calling getSecret would say that secret is undefined.

And, with your current code, adding:

Container.prototype.getSecret2 = function() {
    return this.secret;
}

would return 10. Because your object has now a property called secret when you do

c1.secret = 10;

But remember:

var secret = 3; does not attach the variable to the current object. It just create a variable that live in the current scope. Every function declared in that scope will have access to it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top