“this” keyword in JavaScript

20 / Dec / 2012 by Amit Kumar 0 comments

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.

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.

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.

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.

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.

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

FOUND THIS USEFUL? SHARE IT

Leave a comment -