Javascript this keyword

The this keyword references the object of which the function is a property. In other words, the this references the object that is currently calling the function.

When this is used alone, the owner is the Global object, so this refers to the Global object. In a browser window the Global object is the Window object.

this in global object

/*
* Global this
* Alone, this refers to the global object.
*/
var pageName = "This Keyword";

function showPageName(){
    console.log("pageName: " + this.pageName);//This Keyword
}

showPageName();

 

this in a method

JavaScript “strict mode” does not allow default binding. So, when this is used in a function, in strict mode, this is undefined.

/**
* In a method, this refers to the owner object
*/

let person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {// person is the owner of this function
        return this.firstName + " " + this.lastName;
    }
};

console.log("fullName: "+person.fullName());//John Doe

this in an arrow function

If this is used in an arrow function, this is referencing outer  fields or methods.

/*
* this in arrow funciton
* Arrow functions are special: they don’t have their “own” this. 
* If we reference this from such a function, it’s taken from the outer “normal” function.
*/

let user = {
    name: "Folau",
    sayHi() {

        //If we reference this from such a function, it’s taken from the outer “normal” function.
        let arrow = () => console.log("arrow name: "+this.name);//arrow name: Folau
        arrow();

        function sayMyName(){
            console.log("my name: "+this.name);//my name: 
        }
        sayMyName();
    }
};

user.sayHi();

 

Source code with Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *