Javascript call() & apply() vs bind()?

后端 未结 22 1941
醉话见心
醉话见心 2020-11-22 02:42

I already know that apply and call are similar functions which setthis (context of a function).

The difference is with the way

相关标签:
22条回答
  • 2020-11-22 03:16

    Answer in SIMPLEST form

    • Call invokes the function and allows you to pass in arguments one by one.
    • Apply invokes the function and allows you to pass in arguments as an array.
    • Bind returns a new function, allowing you to pass in a this array and any number of arguments.

    Apply vs. Call vs. Bind Examples

    Call

    var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
    var person2 = {firstName: 'Kelly', lastName: 'King'};
    
    function say(greeting) {
        console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
    }
    
    say.call(person1, 'Hello'); // Hello Jon Kuperman
    say.call(person2, 'Hello'); // Hello Kelly King
    

    Apply

    var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
    var person2 = {firstName: 'Kelly', lastName: 'King'};
    
    function say(greeting) {
        console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
    }
    
    say.apply(person1, ['Hello']); // Hello Jon Kuperman
    say.apply(person2, ['Hello']); // Hello Kelly King
    

    Bind

    var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
    var person2 = {firstName: 'Kelly', lastName: 'King'};
    
    function say() {
        console.log('Hello ' + this.firstName + ' ' + this.lastName);
    }
    
    var sayHelloJon = say.bind(person1);
    var sayHelloKelly = say.bind(person2);
    
    sayHelloJon(); // Hello Jon Kuperman
    sayHelloKelly(); // Hello Kelly King
    

    When To Use Each

    Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.

    I always remember which one is which by remembering that Call is for comma (separated list) and Apply is for Array.

    Bind is a bit different. It returns a new function. Call and Apply execute the current function immediately.

    Bind is great for a lot of things. We can use it to curry functions like in the above example. We can take a simple hello function and turn it into a helloJon or helloKelly. We can also use it for events like onClick where we don’t know when they’ll be fired but we know what context we want them to have.

    Reference: codeplanet.io

    0 讨论(0)
  • 2020-11-22 03:17

    The basic difference between Call, Apply and Bind are:

    Bind will be used if you want your execution context to come later in the picture.

    Ex:

    var car = { 
      registrationNumber: "007",
      brand: "Mercedes",
    
      displayDetails: function(ownerName){
        console.log(ownerName + ' this is your car ' + '' + this.registrationNumber + " " + this.brand);
      }
    }
    car.displayDetails('Nishant'); // **Nishant this is your car 007 Mercedes**
    

    Let's say i want use this method in some other variable

    var car1 = car.displayDetails('Nishant');
    car1(); // undefined
    

    To use the reference of car in some other variable you should use

    var car1 = car.displayDetails.bind(car, 'Nishant');
    car1(); // Nishant this is your car 007 Mercedes
    

    Let's talk about more extensive use of bind function

    var func = function() {
     console.log(this)
    }.bind(1);
    
    func();
    // Number: 1
    

    Why? Because now func is bind with Number 1, if we don't use bind in that case it will point to Global Object.

    var func = function() {
     console.log(this)
    }.bind({});
    
    func();
    // Object
    

    Call, Apply are used when you want to execute the statement at the same time.

    var Name = { 
        work: "SSE",
        age: "25"
    }
    
    function displayDetails(ownerName) {
        console.log(ownerName + ", this is your name: " + 'age' + this.age + " " + 'work' + this.work);
    }
    displayDetails.call(Name, 'Nishant')
    // Nishant, this is your name: age25 workSSE
    
    // In apply we pass an array of arguments
    displayDetails.apply(Name, ['Nishant'])
    // Nishant, this is your name: age25 workSSE
    
    0 讨论(0)
  • 2020-11-22 03:18

    Imagine, bind is not available. you can easily construct it as follow :

    var someFunction=...
    var objToBind=....
    
    var bindHelper =  function (someFunction, objToBind) {
        return function() {
            someFunction.apply( objToBind, arguments );
        };  
    }
    
    bindHelper(arguments);
    
    0 讨论(0)
  • 2020-11-22 03:20

    call/apply executes function immediately:

    func.call(context, arguments);
    func.apply(context, [argument1,argument2,..]);
    

    bind doesn't execute function immediately, but returns wrapped apply function (for later execution):

    function bind(func, context) {
        return function() {
            return func.apply(context, arguments);
        };
    }
    
    0 讨论(0)
  • 2020-11-22 03:20

    Call apply and bind. and how they are different.

    Lets learn call and apply using any daily terminology.

    You have three automobiles your_scooter , your_car and your_jet which start with the same mechanism (method). We created an object automobile with a method push_button_engineStart.

    var your_scooter, your_car, your_jet;
    var automobile = {
            push_button_engineStart: function (runtime){
            console.log(this.name + "'s" + ' engine_started, buckle up for the ride for ' + runtime + " minutes");
        }
    }
    

    Lets understand when is call and apply used. Lets suppose that you are an engineer and you have your_scooter, your_car and your_jet which did not come with a push_button_engine_start and you wish to use a third party push_button_engineStart.

    If you run the following lines of code, they will give an error. WHY?

    //your_scooter.push_button_engineStart();
    //your_car.push_button_engineStart();
    //your_jet.push_button_engineStart();
    
    
    automobile.push_button_engineStart.apply(your_scooter,[20]);
    automobile.push_button_engineStart.call(your_jet,10);
    automobile.push_button_engineStart.call(your_car,40);
    

    So the above example is successfully gives your_scooter, your_car, your_jet a feature from automobile object.

    Let's dive deeper Here we will split the above line of code. automobile.push_button_engineStart is helping us to get the method being used.

    Further we use apply or call using the dot notation. automobile.push_button_engineStart.apply()

    Now apply and call accept two parameters.

    1. context
    2. arguments

    So here we set the context in the final line of code.

    automobile.push_button_engineStart.apply(your_scooter,[20])

    Difference between call and apply is just that apply accepts parameters in the form of an array while call simply can accept a comma separated list of arguments.

    what is JS Bind function?

    A bind function is basically which binds the context of something and then stores it into a variable for execution at a later stage.

    Let's make our previous example even better. Earlier we used a method belonging to the automobile object and used it to equip your_car, your_jet and your_scooter. Now lets imagine we want to give a separate push_button_engineStart separately to start our automobiles individually at any later stage of the execution we wish.

    var scooty_engineStart = automobile.push_button_engineStart.bind(your_scooter);
    var car_engineStart = automobile.push_button_engineStart.bind(your_car);
    var jet_engineStart = automobile.push_button_engineStart.bind(your_jet);
    
    
    setTimeout(scooty_engineStart,5000,30);
    setTimeout(car_engineStart,10000,40);
    setTimeout(jet_engineStart,15000,5);
    

    still not satisfied?

    Let's make it clear as teardrop. Time to experiment. We will go back to call and apply function application and try storing the value of the function as a reference.

    The experiment below fails because call and apply are invoked immediately, hence, we never get to the stage of storing a reference in a variable which is where bind function steals the show

    var test_function = automobile.push_button_engineStart.apply(your_scooter);

    0 讨论(0)
  • 2020-11-22 03:22

    call() :-- Here we pass the function arguments individually, not in an array format

    var obj = {name: "Raushan"};
    
    var greeting = function(a,b,c) {
        return "Welcome "+ this.name + " to "+ a + " " + b + " in " + c;
    };
    
    console.log(greeting.call(obj, "USA", "INDIA", "ASIA"));
    

    apply() :-- Here we pass the function arguments in an array format

    var obj = {name: "Raushan"};
    
    var cal = function(a,b,c) {
        return this.name +" you got " + a+b+c;
    };
    
    var arr =[1,2,3];  // array format for function arguments
    console.log(cal.apply(obj, arr)); 
    

    bind() :--

           var obj = {name: "Raushan"};
    
           var cal = function(a,b,c) {
                return this.name +" you got " + a+b+c;
           };
    
           var calc = cal.bind(obj);
           console.log(calc(2,3,4));
    
    0 讨论(0)
提交回复
热议问题