Uncaught typeError

When I do this:

const car = {
  numberOfDoors: 4,
  drive: function () {
     console.log(`Get in one of the ${this.numberOfDoors} doors, and let's go!`);
  }
};

var letsRoll = car.drive;

letsRoll();

so now the function is invoked at the global scope and it prints undefined, why does it print undefined? I assumed it would refer to the global window, is it because const is used that we get undefined?

also if I change it, and just run it with
var letsRoll = car.drive();
Now it works, but it throws a type error. Please explain these behaviors. Please provide provide proofs with your explanations thank you.

This invoke the function in the global scope. So this.numberOfDoors is undefined.

You can however bind the context of this to the car object:

var letsRoll = car.drive.bind(car);

letsRoll(); // logs "Get in one of the 4 doors, and let's go!"

alternatively you can assign a variable whatever value is returned from the object functions if you invoke it:

const car = {
  numberOfDoors: 4,
  drive: function () {
     console.log(`Get in one of the ${this.numberOfDoors} doors, and let's go!`);
    // note we add a return here
    return "test";
  }
};

// assign the returned value to letsRoll
var letsRoll = car.drive();

letsRoll() // typeError -> letsRoll is not a function
letsRoll // "test" 

Does it make more sense? :slight_smile:

For a painfully detailed explanation on how this works and why obj.foo doesn’t set this to obj but obj.foo() does, see this section of You Don’t Know JS