Binding this in JavaScript

This is dynamically scoped that is it gets determined where it is called.

In most cases, the value of this is determined by how a function is called (runtime binding). It can’t be set by assignment during execution, and it may be different each time the function is called.

There are 4 ways to use this.

  • Default and Implicit binding this.
  • Explicit binding this.
  • With arrow function binding this
  • With new keyword binding this.
  1. Default and Implicit binding this.

Create object and inside of the object the this keyword will refer to person.

const tim = {
    name: "Tim",
    country: "USA",
    language: "english",
    speak() {
        return this.name + " can speak " + this.language;
    }
}

console.log(tim.speak())
Tim can speak english

2. Explicit binding this.

const mike = {
    name: "Mike",
    country: "Spain",
    language: ["english", "spanish"],
    speak() {
        function innerFunction() {
            return (this.name + " can speak " + this.language);
        }
        return innerFunction.bind(this)
    }
}

console.log(mike.speak()())
Mike can speak english,spanish

3. With arrow function binding this

implicit, and explicit binding This is dynamically scoped that is it get determined where it is called. With arrow functions you can use this like lexically scoped.

const mike = {
    name: "Mike",
    country: "Spain",
    language: ["english", "spanish"],
    speak() {
        const innerFunction = () =>{
            return (this.name + " can speak " + this.language);
        }
        return innerFunction()
    }
}

console.log(mike.speak())
Mike can speak english,spanish

4. With new keyword binding this.

function People(name, country, language){
    this.name = name;
    this.country = country;
    this.language = language;
}

const tim = new People("Tim", "USA", "english")

console.log(tim.country);
USA

Leave a Reply

Your email address will not be published.

ANOTE.DEV