The ABCs of Javascript are:
Using them, we can set what 'this' should refer to, irrespective of
how or where the function gets called. Let's see what would happen in
case of an object.
showName
method is being called through its owner object student, as shown below...const student = {
name: "Rahul",
showName: function(){
console.log(this.name);
}
}
student.showName(); //Rahul
Hence, 'this' used inside the function will refer to the student object. What if we assign the
showName
function to a global scoped variable greetStudent
, and then call it as below...const student = {
name: "Rahul",
showName: function(){
console.log(this.name);
}
}
const greetStudent = student.showName;
greetStudent();
//Does not print Anything
// 'this' refers to global object now
// because greetStudent is global, and hence student.showName is being called globally.
The reference to 'this' changes to the global object, & this can cause unwanted and hard to spot bugs.
To set 'this', we use the ABC of JavaScript.
We can borrow or use the functionality of
showName
method, without having to This is known as Function Borrowing, used to efficiently utilize objects.
const student = {
name: "Rahul",
showName: function(friend1, friend2){
console.log(this.name);
console.log(friend1);
console.log(friend2);
}
}
student.showName.call({name: "Rahul" },"John", "Jane");
// Rahul
// John
// Jane
The call() method sets the reference to 'this' to the owner
object. It can be set to any value in the object which is being passed.
(Arguments can be passed as well)
const student = {
name: "Rahul",
showName: function(friend1, friend2){
console.log(this.name);
console.log(friend1);
console.log(friend2);
}
}
student.showName.apply({name: "Rahul" },["John", "Jane"]);
// Rahul
// John
// Jane
apply()
method is used in the same was as call()
, except that it accepts arguments in array form. const student = {
name: "Rahul",
showName: function(){
console.log(this.name);
}
}
const greetStudent = student.showName({
name: "Rahul from Bind"
})
greetStudent(); // Rahul from Bind
bind()
method used in the same way as to call()
, except that it returns a copy of the function, which can be invoked later. Even when greetStudent
is globally scoped, the reference to 'this' is still set to the student object. 🥂Thanks For Reading | Happy Learning🏄♂️
You can get my weekly newsletter of amazing articles I posted this week and some offers or announcement by subscribing to my newsletter here.