-1

What does this.radioStation refer to in the following code: does 'this.radiostaion' refer to Car or the function chagestation. Your input/ clarification would be appreciated. Any good rule of thumb to clear this up?

var Car = function () {

    var gasolineLevel = 10;

    function useGas (amt) {
        if(gasolineLevel - amt < 0) {
            console.log("out of gas :[");
        } else {
            gasolineLevel -= amt;
        }
    };

    return {
        radioStation: "104.5",

        changeStation: function (station) {
            this.radioStation = station;

        },
        go: function (speed) { useGas(speed); }
    };
};


var Ferrari = Car();


console.log(Ferrari);

console.log(Ferrari.go(2));

console.log(Ferrari.go(10));
prasanth
  • 19,775
  • 3
  • 25
  • 48

1 Answers1

0

In changeStation, this will be whatever it was set to when calling changeStation. In normal functions, this is effectively a hidden argument that's determined by how the function is called.

In that specific example, you never call changeStation, so we can't tell you what this will be if/when you do.

If you called it like this:

var ferrari = Car();
ferrari.changeStation();

...then this would refer to the object created by Car (the one referenced by ferrari, created by the object initializer returned by Car at the end), because we called changeStation as part of a property accessor operation on ferrari.

But if you called it like this:

var ferrari = Car();
var changeStation = ferrari.changeStation;
changeStation();

then this would refer to the global object (in loose mode) or would be undefined (in strict mode).

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639