What is the usage of Function.prototype.bind in JavaScript ?
Last Updated :
26 Mar, 2022
Bind method: Using this method, we can bind an object to a common function, so that gives different result when its needed. The bind() method takes an object as an argument and creates a new function. So basically bind function return function.
Let’s understand when bind method is used.
bind the object with common function
Example 1:
Javascript
<script>
const gfg = {
name: "javascript" ,
content: "prototype" ,
feature: function () {
console.log(
`Help in learning ${ this .name}.
The topic is ${ this .content}`
);
}
}
gfg.feature();
console.log()
let b = gfg.feature;
b();
console.log()
let c = gfg.feature.bind(gfg);
c();
</script>
|
Note: Bind different objects to a common function so that each object can access that function and extra functionality to objects so bind function takes any number of arguments.
Example 2:
Javascript
<script>
const gfg = {
name: "javascript" ,
content: "prototype" ,
}
const gfg1 = {
name: "c++" ,
content: "inheritance" ,
}
const gfg2 = {
name: "java" ,
content: "applet" ,
}
function features(param) {
console.log(`Help in learning ${ this .name}.
The topic is ${ this .content} and
these are help in ${param}`)
}
let bindfunc = features.bind(gfg);
bindfunc( "placement" );
let bindfunc1 = features.bind(gfg2);
bindfunc1( "placement" );
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...