How does this keyword work in JavaScript?
In this tutorial, we will learn how this keyword works in JavaScript.
For JavaScript developers, defining the context that this refers to is one of the most confusing topics.
There are 4 rules which help us to define the context of this:
1. Default Binding
var mythisfun = function() {
console.log(this.x);
}
var x = 199 ;
mythisfun(); //199We defined the variable x in the window context so the output of the mythisfun() call will be 199 because this will refer to window context which it’s the default context.
Here, the output of the mythisfun() call will be 199 because this will refer to the default context.
2. Implicit Binding
var ankit = {
name: 'Ankit',
greet: function(person) {
console.log("Hello " + person +", my name is " + this.name);
}
}
ankit.greet("Mayank"); // Hello Mayank, my name is John
var itbhu = ankit.greet;
itbhu("Mayank"); // Hello Mayank, my name isIn Implicit Binding, The object that is adjacent to the dot(.) is what this keyword will be bound to.
3. Explicit Binding
function expli() {
console.log(this.name);
}
var num = {
name:'Ankit'
}
expli.call(num, arg1, arg2, ...); // AnkitIn some cases, instead of putting a property function reference, the function call uses any particular object for this. Explicit binding is used in this case.
Methods such as bind(), call(), and apply() play a major role in this.
4. New Binding
function newBind() {
/* 1- create a new object using the object literal
var this = {}; */
// 2- methods and properties
this.name = 'Mayank';
this.say = function () {
return "He is " + this.name;
};
// 3- return this;
}
var name = 'Ankit';
var result = new newBind();
console.log(result.name); // 3Object is created with the help of new keyword. this created in this function binds to this object.
Also, read: Round float numbers in JavaScript
Leave a Reply