Domanda

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/

È stato utile?

Soluzione

JavaScript copies by value.

In the first example:

  1. The miles variable is 0.
  2. An object is returned with a miles property that has a copy of 0 in it.
  3. The miles variable is updated (now 50) .
  4. The miles property is read (still 0).

In the second example:

  1. The miles variable is 0.
  2. An object is returned with a miles property containing a function that returns the value of the miles variable.
  3. The miles variable is updated (now 50).
  4. The miles function is called and returns the value of the miles variable (50).

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top