The direction of the object function this

var a = {
  b: {
    m: function() {
      console.log(this.p);
    },
    p: "Hello"
  }
};

var hello = a.b.m;
hello() // undefined
Why is

hello () undefined? Where does the this point now?

May.09,2022

by default, this points to event caller , and calls in any environment point to that environment. Of course, this is changeable
.
var a = {
  b: {
    m: function() {
      console.log(this.p);
    },
    p: 'Hello'
  }
};

var hello = a.b.m;
var hello1 = a.b.m.bind(a);
var hello2 = a.b.m.bind(a.b);
hello() // undefined  thiswindow,windowpundefined
hello1() // undefined  thisaapundefined
hello2() //Hello  abbp

the this at this time points to window, but there is no p attribute on the window object, so undefined

is returned.
Menu