In JavaScript, function binding is an important concept that determines the context of the this
keyword within a function. There are several types of function binding, such as Implicit Binding, Explicit Binding, New Binding, and Window Binding. Understanding how these bindings work is essential for writing efficient and bug-free JavaScript code. In this blog post, we will explore these function binding types with examples to get a better understanding of their usage.
Code
/*
- Implicit Binding
- Explicit Binding
- new Bindidng
- window Binding
*/
//----------------------------------------------
// where is this function invoked?
//----------------------------------------------
// var sayName = function(name) {
// console.log('Hello, ' + name);
// };
// sayName('Vishnu!');
//----------------------------------------------
// Implicit Binding
// var me = {
// name: 'Vishnu',
// age: 25,
// sayName: function() {
// console.log(this.name);
// }
// }
// me.sayName(); // According to implicit binding, `this` keyword is targetting the element left i.e. on the left side of the dot(.), in this case `me`
//----------------------------------------------
// var sayNameMixin = function(obj) {
// obj.sayName = function() {
// console.log(this.name);
// }
// };
// var me = {
// name: 'Vishnu',
// age: 25
// };
// var you = {
// name: 'unknown',
// age: 21
// };
// sayNameMixin(me);
// sayNameMixin(you);
// me.sayName();
// you.sayName();
//----------------------------------------------
// var Person = function(name, age) {
// return {
// name: name,
// age: age,
// sayName: function() {
// console.log(this.name);
// },
// mother: {
// name: 'Mausi',
// sayName: function() {
// console.log(this.name);
// }
// }
// };
// };
// var jim = Person('Jim', 42);
// jim.sayName();
// jim.mother.sayName();
//----------------------------------------------
//----------------------------------------------
// Explicit Binding
// call, apply, bind
// var rand = {
// name: 'rand',
// age: 65,
// // sayName: function() {
// // console.log('My name is ' + this.name);
// // }
// };
// var sayName = function() {
// console.log('My name is ' + this.name);
// };
// sayName.call(rand);
//----------------------------------------------
// var rand = {
// name: 'rand',
// age: 65,
// // sayName: function() {
// // console.log('My name is ' + this.name);
// // }
// };
// var sayName = function(lang1, lang2, lang3) {
// console.log('My name is ' + this.name + ' and I know ' + lang1 + ', ' + lang2 + ', ' + lang3);
// };
// var languages = ['JS', 'C++', 'Python'];
// sayName.call(rand, languages[0], languages[1],languages[2]);
// // .apply is a similar thing as .call
// sayName.apply(rand, languages); // .apply()
//----------------------------------------------
// var rand = {
// name: 'rand',
// age: 65,
// // sayName: function() {
// // console.log('My name is ' + this.name);
// // }
// };
// var sayName = function(lang1, lang2, lang3) {
// console.log('My name is ' + this.name + ' and I know ' + lang1 + ', ' + lang2 + ', ' + lang3);
// };
// var languages = ['JS', 'C++', 'Python'];
// // sayName.call(rand, languages[0], languages[1],languages[2]);
// // .apply is a similar thing as .call
// // sayName.apply(rand, languages); // .apply()
// var newFn = sayName.bind(rand, languages[0], languages[1],languages[2]);
// console.log('HERE');
// newFn();
//----------------------------------------------
//----------------------------------------------
//----------------------------------------------
//----------------------------------------------
//----------------------------------------------
// new Binding
// var Animal = function(color, name, type) {
// this.color = color;
// this.name = name;
// this.type = type;
// }
// var Zebra = new Animal('black and white', 'Zorro', 'Zebra');
// console.log(Zebra);
//----------------------------------------------
// window Binding
var sayAge = function() {
console.log(this.age);
};
var me = {
age: 25
};
// sayAge.call(me);
sayAge();
window.age = 35;
sayAge();
Code Explanation
1. Implicit Binding:
Implicit binding involves the automatic binding of the this
keyword to the object left of the dot (.) when a function is invoked. For example:
javascript
var me = {
name: 'Vishnu',
age: 25,
sayName: function() {
console.log(this.name);
}
}
me.sayName(); // Output: Vishnu
In the above code snippet, the sayName
function is defined inside the me
object. When the sayName
function is invoked using me.sayName()
, the this
keyword refers to the me
object.
2. Explicit Binding:
Explicit binding allows us to explicitly define the context of the this
keyword using functions like call
, apply
, and bind
.
a. Using call
:
The call
function can be used to invoke a function by explicitly setting the value of this
. It also allows passing arguments individually. For example:
javascript
var sayName = function(lang1, lang2, lang3) {
console.log(‘My name is ‘ + this.name + ‘ and I know ‘ + lang1 + ‘, ‘ + lang2 + ‘, ‘ + lang3);
};
var rand = {
name: ‘rand’,
age: 65,
};
var languages = [‘JS’, ‘C++’, ‘Python’];
sayName.call(rand, languages[0], languages[1], languages[2]);
In the above code, the sayName
function is invoked using call
, and the this
keyword is explicitly set to the rand
object. The arguments languages[0]
, languages[1]
, and languages[2]
are passed individually.
b. Using apply
:
The apply
function works the same way as call
, but it accepts an array of arguments instead of individual arguments. For example:
javascript
sayName.apply(rand, languages);
c. Using bind
:
The bind
function is similar to call
, but it returns a new function with the context of this
and predefined arguments. The original function is not immediately invoked. For example:
javascript
var newFn = sayName.bind(rand, languages[0], languages[1], languages[2]);
newFn();
3. New Binding:
The new
keyword in JavaScript is used to create an instance of a constructor function. The this
keyword inside a constructor function refers to the newly created object. For example:
javascript
var Animal = function(color, name, type) {
this.color = color;
this.name = name;
this.type = type;
}
var Zebra = new Animal(‘black and white’, ‘Zorro’, ‘Zebra’);
console.log(Zebra);
In the above code, the Animal
constructor function is used to create a new Zebra
object. Inside the constructor function, this
refers to the newly created Zebra
object.
4. Window Binding:
When the this
keyword is used in a function that is not part of an object or not explicitly bound to any other object, it refers to the global object (usually the window
object in a browser). For example:
javascript
var sayAge = function() {
console.log(this.age);
};
var me = {
age: 25
};
sayAge(); // Output: undefined
window.age = 35;
sayAge(); // Output: 35
In the above code, the sayAge
function is invoked without any explicit object binding. Thus, the this
keyword refers to the global object (window
) where the variable age
is defined.
Conclusion
Understanding function binding in JavaScript is crucial for writing effective and maintainable code. By knowing how to use different binding techniques like Implicit Binding, Explicit Binding, New Binding, and Window Binding, you can control the context of the `this` keyword and avoid unexpected behavior in your code.
Also checkout the following codes.
How to Fix Error in Import Statement for MUI ThemeProvider in React?
How to Create a Bar Chart using React and Chart.js