JavaScript Function.prototype.bind() Method
A function is a set of statements that take inputs, do some specific computation, and produce output. There are various scenarios in programming in which we need to pre-configure this keyword or function arguments and we can easily do that in JavaScript with the help of the bind() method. The bind() method creates a new function based on the function on which it is called. Using the bind() method, we can pre-configure this keyword and arguments for the function using the syntax shown below.
Syntax:
const newFunction = oldFunction.bind(thisArg, arg1, ag2, ..., argN)
Using the above syntax, a new function is created based on the old function with this keyword set to thisArg, and function arguments are preconfigured as arg1, agr2, and so on. The example mentioned below demonstrates the use of the bind() method with the help of an example.
Example:
Javascript
<script>
const car = {
brand: 'Lamborghini' ,
};
const printDetail = function (model, topSpeed) {
console.log(`${ this .brand} ${model} has a
top speed of ${topSpeed} mph`);
};
printDetail( 'Diablo Coatl' , 239);
const lamboPrintDetail = printDetail.bind(car);
lamboPrintDetail( 'Diablo VTTT' , 222);
const reventonPrintDetail
= printDetail.bind(car, 'Reventon ', 221);
// Since the arguments are preconfigured so we don' t
reventonPrintDetail();
</script>
|
Output:
undefined Diablo Coatl has a top speed of 239 mph
Lamborghini Diablo VTTT has a top speed of 222 mph
Lamborghini Reventon has a top speed of 221 mph
Last Updated :
08 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...