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

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

    They all attach this into function (or object) and the difference is in the function invocation (see below).

    call attaches this into function and executes the function immediately:

    var person = {  
      name: "James Smith",
      hello: function(thing) {
        console.log(this.name + " says hello " + thing);
      }
    }
    
    person.hello("world");  // output: "James Smith says hello world"
    person.hello.call({ name: "Jim Smith" }, "world"); // output: "Jim Smith says hello world"
    

    bind attaches this into function and it needs to be invoked separately like this:

    var person = {  
      name: "James Smith",
      hello: function(thing) {
        console.log(this.name + " says hello " + thing);
      }
    }
    
    person.hello("world");  // output: "James Smith says hello world"
    var helloFunc = person.hello.bind({ name: "Jim Smith" });
    helloFunc("world");  // output: Jim Smith says hello world"
    

    or like this:

    ...    
    var helloFunc = person.hello.bind({ name: "Jim Smith" }, "world");
    helloFunc();  // output: Jim Smith says hello world"
    

    apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:

    function personContainer() {
      var person = {  
         name: "James Smith",
         hello: function() {
           console.log(this.name + " says hello " + arguments[1]);
         }
      }
      person.hello.apply(person, arguments);
    }
    personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"                                     
    
    0 讨论(0)
  • 2020-11-22 03:41

    Both Function.prototype.call() and Function.prototype.apply() call a function with a given this value, and return the return value of that function.

    Function.prototype.bind(), on the other hand, creates a new function with a given this value, and returns that function without executing it.

    So, let's take a function that looks like this :

    var logProp = function(prop) {
        console.log(this[prop]);
    };
    

    Now, let's take an object that looks like this :

    var Obj = {
        x : 5,
        y : 10
    };
    

    We can bind our function to our object like this :

    Obj.log = logProp.bind(Obj);
    

    Now, we can run Obj.log anywhere in our code :

    Obj.log('x'); // Output : 5
    Obj.log('y'); // Output : 10
    

    Where it really gets interesting, is when you not only bind a value for this, but also for for its argument prop :

    Obj.logX = logProp.bind(Obj, 'x');
    Obj.logY = logProp.bind(Obj, 'y');
    

    We can now do this :

    Obj.logX(); // Output : 5
    Obj.logY(); // Output : 10
    
    0 讨论(0)
  • 2020-11-22 03:42

    The main concept behind all this methods is Function burrowing.

    Function borrowing allows us to use the methods of one object on a different object without having to make a copy of that method and maintain it in two separate places. It is accomplished through the use of . call() , . apply() , or . bind() , all of which exist to explicitly set this on the method we are borrowing

    1. Call invokes the function immediately and allows you to pass in arguments one by one
    2. Apply invokes the function immediately and allows you to pass in arguments as an array.
    3. Bind returns a new function, and you can invoke/call it anytime you want by invoking a function.

    Below is an example of all this methods

    let name =  {
        firstname : "Arham",
        lastname : "Chowdhury",
    }
    printFullName =  function(hometown,company){
        console.log(this.firstname + " " + this.lastname +", " + hometown + ", " + company)
    }
    

    CALL

    the first argument e.g name inside call method is always a reference to (this) variable and latter will be function variable

    printFullName.call(name,"Mumbai","Taufa");     //Arham Chowdhury, Mumbai, Taufa
    

    APPLY

    apply method is same as the call method the only diff is that, the function arguments are passed in Array list

    printFullName.apply(name, ["Mumbai","Taufa"]);     //Arham Chowdhury, Mumbai, Taufa
    

    BIND

    bind method is same as call except that ,the bind returns a function that can be used later by invoking it (does'nt call it immediately)

    let printMyNAme = printFullName.bind(name,"Mumbai","Taufa");
    
    printMyNAme();      //Arham Chowdhury, Mumbai, Taufa
    

    printMyNAme() is the function which invokes the function

    below is the link for jsfiddle

    https://codepen.io/Arham11/pen/vYNqExp

    0 讨论(0)
  • I think the same places of them are: all of them can change the this value of a function.The differences of them are: the bind function will return a new function as a result; the call and apply methods will execute the function immediately, but apply can accept a array as params,and it will parse the array separated.And also, the bind function can be Currying.

    0 讨论(0)
提交回复
热议问题