Ex 1:console.log(this) // windowthis=== window // truefunctiona() {console.log(this) // windowthis=== window // true }a(); // same as window.a();
In example 1 the function "a" is belongs to window object, so this is reference of window object
Ex 2:constgreet= {welcome:function() {console.log(this) // greetthis=== window // false }};greet.welcome();
In example 2 the function "welcome" is belongs to greet object, this is reference of greet object, so it is not same as window.
Ex 3:constgreet2= { isWindow:this=== window,welcome:function() {console.log(this) // greetthis=== window // false }};console.log(greet2); // same as console.log(window.greet2); // { isWindow: true }
In example 3 "isWindow" property of greet2 object is "true", because greet2 belongs to window object. "this" reference changed for only inside the function of the objects.
Ex 5:var b = { name:'jay',say() {console.log(this)}}var c = { name:'jay',say() {returnfunction() {console.log(this)}}}var d = { name:'jay',say() {return () =>console.log(this)}}b.say() // b objectc.say() // [Function]c.say()() // window// while calling fitst time it will assign the returning function to windo object.d.say() // [Function]d.say()() // d object// arrow function will not conside in which lexical scope it is called// it will considers in which lexical scope it is created.