0

i'm trying to "play" with the this keyword, in order To understand it better. i create an object name "car" with propertie "onRoad", that his value is function as you can see.

var car = {
    color: "black",
    type: "bmw",
    year: 2013,
    onRoad: function onTheRoad() {
        console.log(2017 - this.year);

        function demo() {
            console.log(2020 - this.year);
        }
        demo();
    }
};
car.onRoad();

the this keyword work great in the first function, and my output is 4 Just what I wanted.but for some reason in the "demo" function when i was expected that the output will be 7,instead i get output of NaN. i guess that There is a connection to the this keyword. but i do not understand why it's not refers to the "car" object like in the "onTheRoad" function.(the "demo" function is nested inside "onTheRoad" function). Thanks in advance(:

Nave Hazan
  • 337
  • 3
  • 15
  • well, that's the behaviour. You can't blame Javascript for that. it's within a function for this object. – Akshay Khandelwal Jun 17 '17 at 20:40
  • 1
    Because calling `car.onRoad()` sets `this` to `car`, but calling `demo()` sets `this` to nothing in particular. It's *how you call a function* that determines `this`. – deceze Jun 17 '17 at 20:41
  • Pass the this as a ref, like this: demo(this); basically when you call a function javascript looks at the object which called it and assignes the 'this' reference to it(this is true except some cases like bind). – RunningFromShia Jun 17 '17 at 23:20
  • instead of writing demo() like this, bind it to the car object like this demo.bind(car)(), or demo.apply(car) Calling the function like this allows you to execute it within the context of the object car. – Rick Jun 25 '17 at 02:44

0 Answers0