Reputation: 81
I feel like a beginner here. I don't quite get why this 2 codes behave differently. Can someone explain it please? I feel like i miss some JS mechanic here.
Code1:
function Car(){
var miles = 0;
function drive(dist){
miles = miles+dist;
}
return {
drive:drive,
miles:miles
}
}
var car = new Car;
car.drive(50);
Code2:
function Car(){
var miles = 0;
function drive(dist){
miles = miles+dist;
}
return {
drive:drive,
miles:function(){
return miles;
}
}
}
var car = new Car;
car.drive(50);
So it seams like for code1, JS creates a new scope/closure/whatever....value for miles. Maybe someone smart can provide some background to this behavior.
Fiddle: http://jsfiddle.net/P7Zqv/
Upvotes: 0
Views: 180
Reputation: 783
the first code is returning the variable miles as it is, it is being updated but is not being read because it's in a closure, just as Quentin mentioned, the second code is returning a function that returns a variable known as a getter function in Javascript, you have made your own getter function that returns the updated value, you can read more about getter functions here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects.
in short the first code returns a variable miles and the second code returns a getter function miles() that returns the variable miles. I hope that helps :)
if you try something like this:
CODE 3
function Car()
{
var miles = 0;
function drive(dist)
{
return miles += dist;
}
return {
drive: drive,
miles: miles
};
}
var car = new Car();
car.drive(50); // returns 50 and not undefined
this way when car.drive(50) is called, you will not get an undefined because the function is returning a value.
Upvotes: -1
Reputation: 944430
JavaScript copies by value.
In the first example:
miles
variable is 0
.miles
property that has a copy of 0
in it.miles
variable is updated (now 50
) .miles
property is read (still 0
).In the second example:
miles
variable is 0.miles
property containing a function that returns the value of the miles
variable.miles
variable is updated (now 50
).miles
function is called and returns the value of the miles
variable (50
).Upvotes: 4