Open In App

JavaScript Function.prototype.bind() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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',
    };
 
    // As of now, 'this' keyword refers
    // to 'window' object.
    const printDetail = function (model, topSpeed) {
        console.log(`${this.brand} ${model} has a
        top speed of ${topSpeed} mph`);
    };
 
    // Calling the function without using bind which
    // means 'this' still refers to 'window' object
    // so accessing this.brand will give undefined
    printDetail('Diablo Coatl', 239);
 
    // Creating a new function based on printDetail
    // with 'this' keyword referring to car object
    // so accessing this.brand will give 'Lamborgini'
    const lamboPrintDetail = printDetail.bind(car);
    lamboPrintDetail('Diablo VTTT', 222);
 
    // Creating another function based on printDetail
    // with it's arguments pre-configured and 'this'
    // keyword referring to car object
    const reventonPrintDetail
        = printDetail.bind(car, 'Reventon', 221);
 
    // Since the arguments are preconfigured so we don't
    // need to pass any argument to call this function
    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
Previous
Next
Share your thoughts in the comments
Similar Reads