0

I am trying to write a code in javascript

var x=20;
var a={
  x:10,
  fun:(function(){
        console.log(this);
        function q(){
              console.log(this);
        }
        q();
  })
}
a.fun();

It gives me

Object {x: 10, fun: function}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}.

But I don't understand why last "this" point to the window object. Please help me out how "this" keyword is actually working.

Raman Sahasi
  • 24,890
  • 6
  • 51
  • 66
Pulkit Aggarwal
  • 1,779
  • 3
  • 17
  • 27
  • 1
    `this` depends on how the function is called, not where it is defined. See [Understanding the “this” keyword in JavaScript](https://toddmotto.com/understanding-the-this-keyword-in-javascript/) – Tushar Apr 04 '17 at 05:58
  • First gives you object because you are calling it as `a.` so the context is set to `a`. But in `q`, you are directly calling it and hence it will be set to default value of this (`window` in non-strict mode and `undefined` in strict mode) – Rajesh Apr 04 '17 at 05:59
  • @Rajesh So, what can I do so that last "this" point to the object a. – Pulkit Aggarwal Apr 04 '17 at 06:06
  • Inside `fun`, create a variable `var self = this;` and use it instead of this. If you still wish to use `this`, you can look into `.bind`, but I suggest using `self` instead – Rajesh Apr 04 '17 at 06:15
  • @Rajesh Thank you so much – Pulkit Aggarwal Apr 04 '17 at 06:17

0 Answers0