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

后端 未结 22 2242
醉话见心
醉话见心 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: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
    

提交回复
热议问题