Reputation: 870
I understand that foo is a local var and this.foo is a property of 'this'. I'm curious what are the underlying mechanisms responsible for this behaviour. Looks like JS is creating a new this.foo from foo?:
function Life(){
var foo = 0;
function setFoo(newFoo){ foo = newFoo; }
function getFoo(){ return foo; }
function setFooThis(newFoo){ this.foo = newFoo; }
function getFooThis(){ return this.foo; }
return { setFoo, setFooThis, getFoo, getFooThis }
}
var organism = new Life();
organism.setFoo(23);
organism.setFooThis(45);
console.log(organism.getFoo()); // 23
console.log(organism.getFooThis()); // 45
Upvotes: 1
Views: 51
Reputation: 665000
I'm curious what are the underlying mechanisms responsible for this behaviour.
They just are two different things. One is part of a scope, the other part of an object.
Looks like JS is creating a new this.foo from foo?
No. You are explicitly creating two different things, one with .setFoo(23)
the other with .setFooThis(45)
.
Upvotes: 1
Reputation:
To elaborate on Knitesh's answer:
Your setFooThis
uses this
, which is references the Life
function. The foo
variable in var foo = 0
is a variable that is scoped to the function, but is not set ON the function. Meaning it cannot be accessed outside the function, but it is still not a part of the function.
You can see this in action by creating a function inside the Life
function function printThis(){ return this }
and console.log
it. You will see something along the lines of
Object {
foo: 45,
setFoo: function,
setFooThis: function,
getFoo: function,
getFooThis: function
}
If you want to read more about the this
keyword I recommend checking out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Function_context
Upvotes: 0
Reputation: 1652
organism.getFoo()
returns you the closure value
organism.getFooThis()
returns the instance value.
Upvotes: 0