The this keyword in JavaScript - Must Know JavaScript features every programmer should learn to master the language

The previous days I had a great conversation about the fundamentals of JavaScript, scope, closure, etc.. The this keyword was also a discussion point. I wasn’t 100% sure of the rules that apply to this and I wanted to refresh my memory about the possible ways to use the keyword and for each case identify the owner of this when a function is invoked.

The four, and only four rules about this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    var Car = function (name, age) {
        this.name = name;
        this.age = age;

        this.printAge = function() {
            console.log("The age of the car is " + this.age);
        };
    };

    var car1 = new Car("first car", 4);
    var car2 = new Car("second car", 2);

    car1.printAge();
    car2.printAge();
1
2
3
4
5
6
7
8
    var person1 = {
        name: "Christos",
        shout: function() {
            console.log("Hello, my name is " + this.name);
        }
    }

    person1.shout();

The following example is also 100% valid and shows us once again, that the first question that we have to ask ourselves when dealing with this, is who invoked/ called the function that contains the this.

As you can see, even though we defined this on the global scope (read the next point) we are then binding the function to a property of an object and so the current rule applies and this is bound to its object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    function shout() {
            console.log("Hello, my name is " + this.name);
        }

    var person1 = {
        name: "Christos",
        shout: shout
    }

    var person2 = {
        name: "Areti",
        shout: shout
    }

    person1.shout();
    person2.shout();
1
2
3
4
5
6
7
    var surname = "Monogios";
    function shout() {
        console.log(this.surname);
        console.log(this.age);
    }

    shout();

Conclusion

It is frequently the case, that you try to avoid the use of this because you are not 100% sure, which object will own it during the execution time, when you use it inside a function. With the previous four simple rules, you can identify on every case the owner of this.

comments powered by Disqus