April 9, 2020
Estimated Post Reading Time ~

“this” keyword in JavaScript

There are four patterns of invocation in JavaScript:
1. The method invocation pattern.
2. The function invocation pattern.
3. The constructor invocation pattern.
4. The apply invocation pattern.
1. The Method Invocation Pattern:
When a function is stored as a property of an object, we call it a method. When a method is invoked, this is bound to that object.
1
2
3
4
5
6
7
8
var employee = {
    salary: 25000,
    increaseSalary: function(inc) {
        this.salary += inc || 5000;
    }
};
employee.increaseSalary();
document.writeln(employee.salary);
2. The Function invocation Pattern:
When a function is not the property of an object, this is bound to the global object.
1
2
3
4
5
6
7
8
9
employee.setBonus = function () {
    var that = this;
    var countBonus = function (inc) {
        that.salary += inc || that.salary*0.5;
    };
    countBonus();
};
employee.setBonus();
document.writeln(employee.salary);
3. The Constructor Invocation Pattern:
If a function is invoked with a new prefix, then a new object will be created with a hidden link to the value of the function’s prototype member, and this will be bound to that new object. If the function was invoked with the new prefix and the return value is not an object, then this (the new object) is returned instead.
1
2
3
4
5
6
7
8
var Person = function (name) {
    this.name = name;
    this.getName = function () {
        return this.name;
    };
};
var newPerson = new Person("Amit Thakkar"); // this will refer to newly created Object.
document.writeln(newPerson.getName()); // Amit Thakkar
4. The Apply Invocation Pattern:
The apply method takes two parameters. The first is the value that should be bound to this. The second is an array of parameters.
1
2
3
4
var vigil = {
    name:"Vigil"
};
document.writeln(newPerson.getName.apply(vigil)); // Vigil
Here this is referring to vigil object and there will not be any run-time error even when the number of arguments and the number of parameters do not match. If there are too many argument values, the extra argument values will be ignored. If there are too less argument values, the undefined value will be substituted for the missing values. So here second parameter will be undefined.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.