Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Function.prototype.bind() Method

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',
    };
 
    // 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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments