Thursday, August 26, 2021

What is 'this' variable?

 Regular function call:  In regular function call this variable only points at the global object (window object in browser)

Method call: 'this' variable points to the object that is calling the method.

N.B:'this' variable only assigned a value as soon as object call a method.

Ex:

calculateAge(1990);     

function calculateAge(year) {

    var age = 2021 - year;

    console.log(age);

    console.log(this);

}

output:






here 'this' is pointing to window object because the method is in global execution context .this variable is attached to global execution context.

Another example-

var john={

    name:"nabila",

    age:"28",

    qualification:"banker",

     showInfo:function(){

        console.log(this);

    }   

}

john.showInfo();

output:

{name: "nabila", age: "28", qualification: "banker", showInfo: ƒ}

here, 'this' is pointing to john object because we already know 'this' will refers to the object that called the method .

let's have another example ,

var john = {

    name: "nabila",

    age: "28",

    qualification: "banker",


    showInfo: function () {

        console.log(this);

        function innerFunction() {

            console.log(this);

        }

        innerFunction();

    }

}

john.showInfo();

output:

{name: "nabila", age: "28", qualification: "banker", showInfo: ƒ}

{window: Window, self: Window, document: document, name: "", location: Location, …}

here ,'this' inside innerFunction will point to window object however it is in the method. Because we already know in a regular function call 'this' will point to global object .

No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...