0

In a regular object, this inside a method is pointing to the object itself; in a function call, this is pointing to the caller, sometimes, the Window object if it is called globally. I have no problem with those. What I don't understand is the code snippet below:

function test(){
  function method(){console.log(this);}
  method();
}
test()

Since JavaScript function is also an object, I would expect this inside method function should point to the caller which is test object. However, it is pointed to Window object. Why is that? Can someone help me get a consistent understanding about this magic word this? Thank you!

Jake
  • 71
  • 2
  • 8
  • 1
    Here is a useful rule of thumb: if you have `foo.bar()` then `this === foo`. It's equal to the thing *before* the last dot. So `foo.bar.baz.quux()` will leave you with `this = foo.bar.baz`. If there is nothing before the dot, then you run into "special rules" where `this === undefined` or `this === window` depending on whether you're in strict mode or not. – VLAZ Apr 29 '20 at 13:40
  • it's all about JS closures, in your test function, after declaring method(), add `method = method.bind(this)` and 'this' will always point to the test scope function – developer Apr 29 '20 at 13:41

0 Answers0