我已经知道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()。当您希望立即调用函数并修改上下文时,请使用.call()或.apply()。

Call/apply立即调用该函数,而bind返回的函数在稍后执行时将具有用于调用原始函数的正确上下文设置。这样你就可以在异步回调和事件中维护上下文。

我经常这样做:

function MyObject(element) {
    this.elm = element;

    element.addEventListener('click', this.onClick.bind(this), false);
};

MyObject.prototype.onClick = function(e) {
     var t=this;  //do something with [t]...
    //without bind the context of this function wouldn't be a MyObject
    //instance as you would normally expect.
};

我在Node.js中广泛使用它,用于我想要传递成员方法的异步回调,但仍然希望上下文是启动异步操作的实例。

bind的简单实现如下所示:

Function.prototype.bind = function(ctx) {
    var fn = this;
    return function() {
        fn.apply(ctx, arguments);
    };
};

还有更多关于它的内容(比如传递其他参数),但您可以阅读更多关于它的内容,并查看MDN上的实际实现。


它允许设置该函数的值,而不依赖于函数的调用方式。这在处理回调时非常有用:

  function sayHello(){
    alert(this.message);
  }

  var obj = {
     message : "hello"
  };
  setTimeout(sayHello.bind(obj), 1000);

要用call实现相同的结果,应该是这样的:

  function sayHello(){
    alert(this.message);
  }

  var obj = {
     message : "hello"
  };
  setTimeout(function(){sayHello.call(obj)}, 1000);

TL; diana:

简单地说,bind创建函数,调用和apply执行函数,而apply期望数组中的参数

完整的解释

假设有一个乘法函数

function multiplication(a,b){
console.log(a*b);
}

让我们使用bind创建一些标准函数

var multiby2 = multiplication.bind(this,2);

现在multiby2(b)等于乘法(2,b);

multiby2(3); //6
multiby2(4); //8

如果我在bind中传递两个参数会怎样

var getSixAlways = multiplication.bind(this,3,2);

现在getSixAlways()等于乘法(3,2);

getSixAlways();//6

即使传递参数也返回6; getSixAlways (12);/ / 6

var magicMultiplication = multiplication.bind(this);

这将创建一个新的乘法函数并将其分配给magic乘法。

哦,不,我们将乘法功能隐藏到magic乘法中。

调用 magic乘法返回一个空函数b()

在执行过程中,它运行良好 magicMultiplication (6 5);/ / 30

打电话申请怎么样?

magicMultiplication.call(这3 2);/ / 6

magicMultiplication.apply(这一点,[5,2]);/ / 10


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

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"                                     

function. prototype.call()和function. prototype.apply()都使用给定的这个值调用函数,并返回该函数的返回值。

另一方面,function .prototype.bind()使用给定的这个值创建一个新函数,并返回该函数而不执行它。

让我们取一个这样的函数:

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

现在,让我们选择一个这样的对象:

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

我们可以像这样将函数绑定到对象上:

Obj.log = logProp.bind(Obj);

现在,我们可以在代码中的任何地方运行Obj.log:

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

真正有趣的是,你不仅为this绑定了一个值,还为它的参数prop绑定了一个值:

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

我们现在可以这样做:

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

这里有一篇很好的文章来说明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

我认为它们的相同之处在于:它们都可以改变函数的this值。它们的区别是:绑定函数将返回一个新函数作为结果;call和apply方法将立即执行函数,但apply可以接受数组作为参数,并且它将解析分离的数组。绑定函数也可以是curiling。


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

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绑定函数详细了解


调用/apply立即执行函数:

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

Bind不会立即执行函数,而是返回包装好的apply函数(供以后执行):

function bind(func, context) {
    return function() {
        return func.apply(context, arguments);
    };
}

调用apply和bind。以及它们的不同之处。

让我们学习如何使用日常术语。

你有三辆汽车,你的摩托车,你的汽车和你的喷气式飞机,它们以相同的机制(方法)开始。 我们使用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");
    }
}

让我们理解什么时候使用call和apply。让我们假设你是一名工程师,你有你的摩托车,你的汽车和你的喷气式飞机,这些都没有push_button_engine_start,你希望使用第三方push_button_engineStart。

如果运行以下代码行,它们将给出一个错误。为什么?

//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);

上面的例子成功地给了your_scooter, your_car, your_jet一个automobile对象的特征。

让我们再深入一点 在这里,我们将拆分上面的代码行。 汽车。push_button_engineStart帮助我们获取正在使用的方法。

此外,我们使用点表示法使用apply或call。 automobile.push_button_engineStart.apply ()

现在应用和调用accept两个参数。

上下文 参数

这里我们在最后一行代码中设置了context。

automobile.push_button_engineStart.apply (your_scooter [20])

call和apply的区别在于apply接受数组形式的形参,而call只能接受以逗号分隔的参数列表。

什么是JS绑定函数?

绑定函数基本上就是绑定某个东西的上下文,然后将其存储到一个变量中,以便在稍后阶段执行。

让我们把前面的例子做得更好。之前我们使用了一个属于automobile对象的方法,并使用它来装备你的car、你的jet和你的scooter。现在让我们想象一下,我们想要分别给出一个单独的push_button_engineStart,在我们希望的执行的任何后续阶段分别启动我们的汽车。

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);

还不满意?

让我们像泪滴一样说清楚。是时候做实验了。我们将返回到调用和应用函数应用程序,并尝试将函数的值存储为引用。

下面的实验失败了,因为call和apply是立即调用的,因此,我们从来没有达到在变量中存储引用的阶段,这是bind函数的亮点

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


语法

呼叫(thisArg, arg1, arg2, .) (thisArg专心,argsArray) bind(thisArg[, arg1] [, arg2])

Here

thisArg是对象 argArray是一个数组对象 Arg1, arg2, arg3,…是额外的参数

function printBye(message1, message2){ console.log(message1 + " " + this.name + " "+ message2); } var par01 = { name:"John" }; var msgArray = ["Bye", "Never come again..."]; printBye.call(par01, "Bye", "Never come again..."); //Bye John Never come again... printBye.call(par01, msgArray); //Bye,Never come again... John undefined //so call() doesn't work with array and better with comma seperated parameters //printBye.apply(par01, "Bye", "Never come again...");//Error printBye.apply(par01, msgArray); //Bye John Never come again... var func1 = printBye.bind(par01, "Bye", "Never come again..."); func1();//Bye John Never come again... var func2 = printBye.bind(par01, msgArray); func2();//Bye,Never come again... John undefined //so bind() doesn't work with array and better with comma seperated parameters


最简单形式的答案

调用函数并允许您逐个传入参数 一个。 Apply调用函数并允许传入参数 作为一个数组。 Bind返回一个新函数,允许传入 此数组和任意数量的参数。


应用、调用和绑定示例

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

应用

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

什么时候使用

Call和apply是可以互换的。只需要决定发送一个数组还是一个以逗号分隔的参数列表更容易。

我总是记住哪个是哪个,记住Call是为逗号(分隔列表)和Apply是为数组。

Bind有点不同。它返回一个新函数。Call和Apply立即执行当前函数。

Bind对很多事情都很有用。我们可以像上面的例子一样使用它来curry函数。我们可以使用一个简单的hello函数,并将其转换为helloJon或helloKelly。我们也可以将它用于像onClick这样的事件,我们不知道它们什么时候会被触发,但我们知道我们想让它们拥有什么上下文。

参考:codeplanet.io


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

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

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


    function sayHello() {
            //alert(this.message);
            return this.message;
    }
    var obj = {
            message: "Hello"
    };

    function x(country) {
            var z = sayHello.bind(obj);
            setTimeout(y = function(w) {
//'this' reference not lost
                    return z() + ' ' + country + ' ' + w;
            }, 1000);
            return y;
    }
    var t = x('India')('World');
    document.getElementById("demo").innerHTML = t;

我之前创建了函数对象、函数调用、call/apply和bind之间的比较:

.bind允许您现在设置this值,同时允许您在将来执行该函数,因为它返回一个新的函数对象。


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


Call, Apply和Bind之间的基本区别是:

如果您希望执行上下文出现在图的后面,则将使用Bind。

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**

假设我想在其他变量上使用这个方法

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

在你应该使用的其他变量中使用car的引用

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

让我们讨论bind函数的更广泛使用

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

func();
// Number: 1

为什么?因为现在func与编号1绑定,如果我们不使用bind,它将指向全局对象。

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

func();
// Object

当您希望同时执行语句时,将使用Call、Apply。

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

call():——这里我们单独传递函数参数,而不是数组格式

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():——这里我们以数组格式传递函数参数

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));

JavaScript调用()

const person = {
    name: "Lokamn",
    dob: 12,
    print: function (value,value2) {
        console.log(this.dob+value+value2)
    }
}
const anotherPerson= {
     name: "Pappu",
     dob: 12,
}
 person.print.call(anotherPerson,1,2)

JavaScript应用()

    name: "Lokamn",
    dob: 12,
    print: function (value,value2) {
        console.log(this.dob+value+value2)
    }
}
const anotherPerson= {
     name: "Pappu",
     dob: 12,
}
 person.print.apply(anotherPerson,[1,2])

**call和apply函数是不同的,调用单独的参数,但应用数组 如:(1、2、3) **

JavaScript绑定()

    name: "Lokamn",
    dob: 12,
    anotherPerson: {
        name: "Pappu",
        dob: 12,
        print2: function () {
            console.log(this)
        }
    }
}

var bindFunction = person.anotherPerson.print2.bind(person)
 bindFunction()

所有这些方法背后的主要概念是函数挖掘。

函数借用允许我们在不同的对象上使用一个对象的方法,而不必复制该方法并在两个不同的地方维护它。它是通过使用。调用(),。Apply(),或。Bind(),所有这些方法的存在都是为了显式地在我们所借用的方法上设置此值

Call立即调用函数,并允许您逐个传入参数 一个 Apply立即调用函数,并允许传入参数 作为一个数组。 Bind返回一个新函数,您可以通过调用函数随时调用/调用它。

下面是所有这些方法的示例

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

CALL

第一个参数,例如调用方法中的name总是一个引用 To (this)变量和后者将是函数变量

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

应用

Apply方法与call方法相同 唯一的区别是,函数参数是在数组列表中传递的

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

BIND

Bind方法与call方法相同,不同之处在于,Bind返回一个可以稍后通过调用它来使用的函数(不立即调用它)。

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

printMyNAme();      //Arham Chowdhury, Mumbai, Taufa

printMyNAme()是调用该函数的函数

下面是jsfiddle的链接

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


在以后调用该函数时使用bind。apply和call都调用函数。

Bind()还允许将附加的参数挂在args数组上。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind


简单来说,所有方法都用于在常规函数中显式地设置上下文(this)

Call: Call调用给定上下文的函数,并允许一个一个地传递参数

Apply: Apply在给定上下文调用函数,并允许将参数作为数组传递

Bind: Bind通过设置提供的上下文返回一个新函数,并允许逐个传递参数

注:

Call和Apply都是相似的,唯一不同的是它们期望参数的方式 上述方法不适用于箭头函数


JavaScript中call()、apply()和bind()方法的第一个区别是它们的执行时间! Call()和apply()是相似的立即执行,而bind()创建了一个新函数,我们必须在任何稍后的时间显式调用!

另一个区别是,在传递参数时,call()允许我们用逗号分隔一个一个地传递,apply()允许我们作为参数数组传递,而bind()允许我们两者都做!

我已附上下面的示例代码!

const person = {
    fullName : function (randomMessage) {
        return `Hello, ${this.firstName} ${this.lastName} ${randomMessage}`;
    }
}

const personOne = {
    firstName : "John",
    lastName : "Doe"
}

const personTwo = {
    firstName : "Jack",
    lastName : "Adhikari"
}

let fullNameBind = person.fullName.bind(personOne, "--Binding");
let fullNameCall = person.fullName.call({firstName : "Sarah", lastName: "Holmes"}, "--Calling");
let fullNameApply = person.fullName.apply(personTwo, ["--Applying"]);

console.log(fullNameBind());
console.log(fullNameCall);
console.log(fullNameApply);