Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript Function.prototype.bind() Method

  • Last Updated : 07 Oct, 2021

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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 refering 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 refering 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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!