0

Here why this pointing to global object(window).
I know that using arrow function or closure or call/apply/bind, I can make it point to person object.
But I am not at all clear that why this pointing to global object(window).

var person={
  name:'xyz',
  printName: function() {
    function displayName() {
        console.log(this);
    }
    displayName();
  }
}
person.printName();
pankaj
  • 149
  • 9
  • This is a non-strict speciality, it should be `undefined`. – ASDFGerte Mar 31 '21 at 13:25
  • `displayName()` is itself a traditional function, so calling the function follows all the normal rules for binding `this`. – Pointy Mar 31 '21 at 13:25
  • 1
    In `a.b()`, the `this` in `b` is `a`, by dint of `a` coming before the `.`. When there is no `.`, there's no `this`/it's implicitly the global object. – deceze Mar 31 '21 at 13:25
  • @Pointy I am new to javascript! as per my understanding displayName is invoked & declared under person object so it should point person. Can you please guide further or please provide any reference link where this particular point can become clear to me? – pankaj Mar 31 '21 at 13:30
  • 1
    No, it's declared *inside* a method on `person`, and then called without a reference to any context object. The function really has no relationship to the `person` object at all. – Pointy Mar 31 '21 at 13:31
  • @Pointy yeah but as per my understand its nearest outer context should person and then window. sorry to ask silly questions but trying to understand ;) – pankaj Mar 31 '21 at 13:34
  • 2
    The crucial thing to understand is that the `this` is decided *by how the function is called*. It doesn't matter at all where or how it's declared. `displayName()` doesn't have a `this` because it's called as `displayName()`. If you do `this.foo = displayName; this.foo()`, now it has a `this` because it's been called as `this.foo()`. Refer back to my [previous comment](https://stackoverflow.com/questions/66888770/why-this-pointing-to-global-object?noredirect=1#comment118236729_66888770)… – deceze Mar 31 '21 at 13:35
  • @deceze thanks clear now :) – pankaj Mar 31 '21 at 13:39

0 Answers0