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.
.secretis a property of the object, the other is a private variable due to the scope of the function within it's declared. Remember that functions in JS are treated like objects!var secret) is accessible in the scope it is declared (in eachContainerinstance). You set a property (getSecret), by usingthis, which is in the same scope assecret, so you can access it from there. In the scope where you declarec1(global, I'm guessing), it doesn't have access to thesecretvariable. Then you dynamically set a "secret" property on a specific instance withc1.secret = 10;, which is shown by the console output.