this

this is a object reference to its parent object.

  • In creation phase this points to window object.

  • this will represents the object it belongs to.

Ex 1:
    console.log(this) // window
    this === window // true
    
    function a() {
        console.log(this) // window
        this === 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:
const greet = {
    welcome: function() {
        console.log(this) // greet
        this === 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:

const greet2 = {
    isWindow: this === window,
    welcome: function() {
        console.log(this) // greet
        this === 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 4:
const name = "Vijay";
function person() {
    console.log(this.name);
}

const firstPerson = {
    name: "Deepak",
    person: person
}

const secondPerson = {
    name: "Vishnu",
    person: person
}

person(); // Vijay

firstPerson.person(); // Deepak

secondPerson.person(); // Vishnu

Ex 5:
var b = {
  name: 'jay',
  say() {console.log(this)}
}

var c = {
  name: 'jay',
  say() {return function() {console.log(this)}}
}

var d = {
  name: 'jay',
  say() {return () => console.log(this)}
}

b.say() // b object

c.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.

Last updated