我已经知道apply和call是类似的函数,它们设置this(函数的上下文)。

区别在于我们发送参数的方式(manual vs array)

问题:

但是什么时候应该使用bind()方法呢?

var obj = {
  x: 81,
  getX: function() {
    return this.x;
  }
};

alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));

jsbin


当前回答

这里有一篇很好的文章来说明bind()、apply()和call()之间的区别,总结如下。

bind() allows us to easily set which specific object will be bound to this when a function or method is invoked. // This data variable is a global variable​ var data = [ {name:"Samantha", age:12}, {name:"Alexis", age:14} ] var user = { // local data variable​ data :[ {name:"T. Woods", age:37}, {name:"P. Mickelson", age:43} ], showData:function (event) { var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​ console.log (this.data[randomNum].name + " " + this.data[randomNum].age); } } // Assign the showData method of the user object to a variable​ var showDataVar = user.showData; showDataVar (); // Samantha 12 (from the global data array, not from the local data array)​ /* This happens because showDataVar () is executed as a global function and use of this inside showDataVar () is bound to the global scope, which is the window object in browsers. */ // Bind the showData method to the user object​ var showDataVar = user.showData.bind (user); // Now the we get the value from the user object because the this keyword is bound to the user object​ showDataVar (); // P. Mickelson 43​ bind() allow us to borrow methods // Here we have a cars object that does not have a method to print its data to the console​ var cars = { data:[ {name:"Honda Accord", age:14}, {name:"Tesla Model S", age:2} ] } // We can borrow the showData () method from the user object we defined in the last example.​ // Here we bind the user.showData method to the cars object we just created.​ cars.showData = user.showData.bind (cars); cars.showData (); // Honda Accord 14​ One problem with this example is that we are adding a new method showData on the cars object and we might not want to do that just to borrow a method because the cars object might already have a property or method name showData. We don’t want to overwrite it accidentally. As we will see in our discussion of Apply and Call below, it is best to borrow a method using either the Apply or Call method. bind() allow us to curry a function Function Currying, also known as partial function application, is the use of a function (that accept one or more arguments) that returns a new function with some of the arguments already set. function greet (gender, age, name) { // if a male, use Mr., else use Ms.​ var salutation = gender === "male" ? "Mr. " : "Ms. "; if (age > 25) { return "Hello, " + salutation + name + "."; }else { return "Hey, " + name + "."; } } We can use bind() to curry this greet function // So we are passing null because we are not using the "this" keyword in our greet function. var greetAnAdultMale = greet.bind (null, "male", 45); greetAnAdultMale ("John Hartlove"); // "Hello, Mr. John Hartlove." var greetAYoungster = greet.bind (null, "", 16); greetAYoungster ("Alex"); // "Hey, Alex."​ greetAYoungster ("Emma Waterloo"); // "Hey, Emma Waterloo." apply() or call() to set this value The apply, call, and bind methods are all used to set the this value when invoking a method, and they do it in slightly different ways to allow use direct control and versatility in our JavaScript code. The apply and call methods are almost identical when setting the this value except that you pass the function parameters to apply () as an array, while you have to list the parameters individually to pass them to the call () method. Here is one example to use call or apply to set this in the callback function. // Define an object with some properties and a method​ // We will later pass the method as a callback function to another function​ var clientData = { id: 094545, fullName: "Not Set", // setUserName is a method on the clientData object​ setUserName: function (firstName, lastName) { // this refers to the fullName property in this object​ this.fullName = firstName + " " + lastName; } }; function getUserInput (firstName, lastName, callback, callbackObj) { // The use of the Apply method below will set the "this" value to callbackObj​ callback.apply (callbackObj, [firstName, lastName]); } // The clientData object will be used by the Apply method to set the "this" value​ getUserInput ("Barack", "Obama", clientData.setUserName, clientData); // the fullName property on the clientData was correctly set​ console.log (clientData.fullName); // Barack Obama Borrow functions with apply or call Borrow Array methods Let’s create an array-like object and borrow some array methods to operate on the our array-like object. // An array-like object: note the non-negative integers used as keys​ var anArrayLikeObj = {0:"Martin", 1:78, 2:67, 3:["Letta", "Marieta", "Pauline"], length:4 }; // Make a quick copy and save the results in a real array: // First parameter sets the "this" value​ var newArray = Array.prototype.slice.call (anArrayLikeObj, 0); console.log (newArray); // ["Martin", 78, 67, Array[3]]​ // Search for "Martin" in the array-like object​ console.log (Array.prototype.indexOf.call (anArrayLikeObj, "Martin") === -1 ? false : true); // true​ Another common case is that convert arguments to array as following // We do not define the function with any parameters, yet we can get all the arguments passed to it​ function doSomething () { var args = Array.prototype.slice.call (arguments); console.log (args); } doSomething ("Water", "Salt", "Glue"); // ["Water", "Salt", "Glue"] Borrow other methods var gameController = { scores :[20, 34, 55, 46, 77], avgScore:null, players :[ {name:"Tommy", playerID:987, age:23}, {name:"Pau", playerID:87, age:33} ] } var appController = { scores :[900, 845, 809, 950], avgScore:null, avg :function () { var sumOfScores = this.scores.reduce (function (prev, cur, index, array) { return prev + cur; }); this.avgScore = sumOfScores / this.scores.length; } } // Note that we are using the apply () method, so the 2nd argument has to be an array​ appController.avg.apply (gameController); console.log (gameController.avgScore); // 46.4​ // appController.avgScore is still null; it was not updated, only gameController.avgScore was updated​ console.log (appController.avgScore); // null​ Use apply() to execute variable-arity function

的数学。Max是变量函数的一个例子,

// We can pass any number of arguments to the Math.max () method​
console.log (Math.max (23, 11, 34, 56)); // 56

但是如果我们有一个数字数组要传递给Math.max呢?我们不能这样做:

var allNumbers = [23, 11, 34, 56];
// We cannot pass an array of numbers to the the Math.max method like this​
console.log (Math.max (allNumbers)); // NaN

这就是apply()方法帮助我们执行可变函数的地方。与上述方法不同,我们必须使用apply()传递数字数组,如下所示:

var allNumbers = [23, 11, 34, 56];
// Using the apply () method, we can pass the array of numbers:
console.log (Math.max.apply (null, allNumbers)); // 56

其他回答

bind:它将函数与所提供的值和上下文绑定,但不执行函数。要执行函数,需要调用函数。

调用:它使用提供的上下文和参数执行函数。

apply:它使用提供的上下文和执行函数 参数作为数组。

想象一下,绑定是不可用的。 你可以简单地构建如下:

var someFunction=...
var objToBind=....

var bindHelper =  function (someFunction, objToBind) {
    return function() {
        someFunction.apply( objToBind, arguments );
    };  
}

bindHelper(arguments);

当我们想要分配一个具有特定上下文的函数时,应该使用Bind函数。

var demo = {
           getValue : function(){ 
             console.log('demo object get value       function') 
            }
           setValue : function(){  
              setTimeout(this.getValue.bind(this),1000)           
           }
 }

在上面的例子中,如果我们调用demo.setValue()函数并传递这个。getValue函数,那么它不会调用demo。setValue函数,因为setTimeout中的this指向窗口对象,所以我们需要将演示对象context传递给this。getValue函数使用bind。这意味着我们只是将demo对象的上下文传递给function,而不是实际调用function。

希望你能理解。

更多信息请参考 Javascript绑定函数详细了解

它们都将其附加到函数(或对象)中,区别在于函数调用(见下文)。

Call将此附加到函数中并立即执行函数:

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将它附加到函数中,需要像这样单独调用:

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"

或者像这样:

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

Apply类似于call,只是它接受一个类似数组的对象,而不是一次列出一个参数:

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"                                     

Call:调用函数,允许你一个一个地传递参数

Apply: Apply调用函数并允许您将参数作为数组传递

Bind: Bind返回一个新函数,允许传入this数组和任意数量的参数。

var person1 = {firstName: 'Raju', lastName: 'king'}; var person2 = {firstName: 'chandu', lastName: 'shekar'}; function greet(greeting) { console.log(greeting + ' ' + this.firstName + ' ' + this.lastName); } function greet2(greeting) { console.log( 'Hello ' + this.firstName + ' ' + this.lastName); } greet.call(person1, 'Hello'); // Hello Raju king greet.call(person2, 'Hello'); // Hello chandu shekar greet.apply(person1, ['Hello']); // Hello Raju king greet.apply(person2, ['Hello']); // Hello chandu shekar var greetRaju = greet2.bind(person1); var greetChandu = greet2.bind(person2); greetRaju(); // Hello Raju king greetChandu(); // Hello chandu shekar