JavaScript call()&Application()vs bind()?

我已经知道applycall是设置this(函数的上下文)的类似函数。

区别在于我们发送参数的方式(手动与数组)

提问:

但是什么时候应该使用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

557652 次浏览

当您希望稍后使用特定上下文调用该函数时,请使用.bind(),这在事件中很有用。当您想立即调用函数时,请使用.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

它允许独立于函数的调用方式设置this的值。这在使用回调时非常有用:

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

太长别读:

简单地说,bind创建函数,调用和应用执行函数,而应用需要数组中的参数

完整解释

假设我们有multiplication函数

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

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

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

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

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

如果我在bind中传递两个参数怎么办

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

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

getSixAlways();//6

偶数传递参数返回6;getSixAlways(12); //6

var magicMultiplication = multiplication.bind(this);

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

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

呼叫magicMultiplication返回一个空白function b()

执行时效果很好magicMultiplication(6,5); //30

打电话申请怎么样?

magicMultiplication.call(this,3,2); //6

magicMultiplication.apply(this,[5,2]); //10

它们都将这个附加到函数(或对象)中,不同之处在于函数调用(见下文)。

打电话这个附加到函数中并立即执行该函数:

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"

绑定这个附加到函数中,它需要像这样单独调用:

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"

适用类似于打电话,只是它接受一个类似数组的对象,而不是一次列出一个参数:

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#1都使用给定的this值调用函数,并返回该函数的返回值。

另一方面,#0使用给定的this值创建一个新函数,并返回该函数而不执行它。

所以,让我们取一个看起来像这样的函数:

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 : 5Obj.log('y'); // Output : 10

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

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

我们现在可以这样做:

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

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

  • bind()允许我们在调用函数或方法时轻松设置哪个特定对象将绑定到这个

    // 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 insideshowDataVar () 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​

    这个例子的一个问题是我们在cars对象上添加了一个新方法showData我们可能不想这样做只是为了借用一个方法,因为汽车对象可能已经有一个属性或方法名称showData。我们不想意外地覆盖它。正如我们将在下面对ApplyCall的讨论中看到的,最好使用ApplyCall方法借用方法。

  • bind()允许我们柯里化一个函数

    函数咖喱,也称为部分函数应用,是使用函数(接受一个或多个参数)返回一个新函数,其中一些参数已经设置。

    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 + ".";}}

    我们可以使用bind()来curry这个greet函数

    // 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 slightlydifferent 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​

      另一种常见的情况是将arguments转换为数组,如下所示

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

The Math.max is one example of variable-arity function,

// 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值。它们的不同之处在于:绑定函数将返回一个新函数作为结果;调用和应用方法将立即执行该函数,但应用可以接受一个数组作为参数,它将解析分离的数组。此外,绑定函数可以是柯林。

想象一下,绑定不可用。您可以按照以下方式轻松构建它:

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()函数并直接传递this.getValue函数,那么它不会直接调用demo.setValue函数,因为setTimeout中的this指的是windows对象,所以我们需要使用bind将演示对象上下文传递给this.getValue函数。

希望你能理解。

更多信息请参考javascript bind函数详细了解

呼叫/申请立即执行函数:

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

绑定不会立即执行函数,但返回包装的适用函数(供以后执行):

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

调用应用和绑定。以及它们是如何不同的。

让我们学习使用任何日常术语调用和应用。

您有三个汽车your_scooter , your_car and your_jet,它们以相同的机制(方法)开始。我们用方法push_button_engineStart创建了一个对象automobile

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

让我们了解何时调用和应用使用。假设您是一名工程师,并且您有your_scooteryour_caryour_jet没有附带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帮助我们获取正在使用的方法。

此外,我们使用点符号使用应用或调用。automobile.push_button_engineStart.apply()

现在应用和调用接受两个参数。

  1. 背景
  2. 参数

所以这里我们在最后一行代码中设置上下文。

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

调用和应用的区别只是应用程序接受数组形式的参数,而调用只是可以接受逗号分隔的参数列表。

什么是JS Bind函数?

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

让我们把前面的例子做得更好。前面我们使用了一个属于汽车对象的方法并使用它来装备your_car, your_jet and your_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);

还不满意?

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

下面的实验失败了,因为调用和应用被立即调用,因此,我们永远不会进入将引用存储在变量中的阶段,这是bind函数窃取显示的地方

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

语法

  • 打电话(这是Arg, Arg, Arg, Arg,…)
  • 适用(thisArg, artsArray)取值范围取值范围取值范围
  • 绑定(thisArg[, ard1[, ard2[,…]]])

这里

  • 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

以最简单的形式回答

  • 打电话调用函数并允许您逐个传入参数一。
  • 申请调用函数并允许您传入参数作为数组。
  • 绑定返回一个新函数,允许您传入一个这个数组和任意数量的参数。

应用vs.调用vs.绑定示例

打电话

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 Kupermansay.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 Kupermansay.apply(person2, ['Hello']); // Hello Kelly King

绑定

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 KupermansayHelloKelly(); // Hello Kelly King

何时使用每个

调用和应用是非常可互换的。只需决定是以数组还是以逗号分隔的参数列表发送更容易。

我总是记住哪一个是哪一个,记住Call是逗号(分隔列表),Ap唱是数组。

Bind有点不同。它返回一个新函数。调用并应用立即执行当前函数。

Bind在很多方面都很棒。我们可以用它来像上面的例子中那样柯里化函数。我们可以把一个简单的hello函数变成helloJon或helloKelly。我们也可以把它用于像onClick这样的事件,我们不知道它们什么时候会被触发,但我们知道我们希望它们有什么上下文。

参考:codeplanet.io

绑定:它使用提供的值和上下文绑定函数,但不执行函数。要执行函数,您需要调用该函数。

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

适用:它使用提供的上下文执行函数参数为数组

    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 lostreturn z() + ' ' + country + ' ' + w;}, 1000);return y;}var t = x('India')('World');document.getElementById("demo").innerHTML = t;

我在不久前创建了函数对象、函数调用、call/applybind之间的比较:

在此处输入图片描述

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

呼叫:调用调用函数并允许您一个接一个地传递参数

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

绑定: 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 kinggreet.call(person2, 'Hello'); // Hello chandu shekar


greet.apply(person1, ['Hello']); // Hello Raju kinggreet.apply(person2, ['Hello']); // Hello chandu shekar
var greetRaju = greet2.bind(person1);var greetChandu = greet2.bind(person2);
greetRaju(); // Hello Raju kinggreetChandu(); // Hello chandu shekar

调用、应用和绑定的基本区别是:

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

例如:

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绑定,如果我们在这种情况下不使用绑定,它将指向全局对象。

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

当您想同时执行语句时,可以使用Call、Ap唱。

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 argumentsdisplayDetails.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"));

应用():--这里我们以数组格式传递函数参数

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 argumentsconsole.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])

**调用和应用函数是不同的调用采取单独的参数,但应用采取数组喜欢:[1,2,3]**

JavaScript bind()

    name: "Lokamn",dob: 12,anotherPerson: {name: "Pappu",dob: 12,print2: function () {console.log(this)}}}
var bindFunction = person.anotherPerson.print2.bind(person)bindFunction()

所有这些方法背后的主要概念是功能挖掘

函数借用允许我们在不同的对象上使用一个对象的方法,而无需复制该方法并将其维护在两个不同的地方。它是通过使用. call() , . 应用()或. bind()来实现的,所有这些都存在于我们借用的方法上显式设置它

  1. 打电话立即调用该函数,并允许您逐个传入参数一个
  2. 申请立即调用该函数并允许您传入参数阵列.
  3. 绑定返回一个新函数,您可以随时通过调用函数来调用/调用它。

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

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

调用

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

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

申请

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

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来调用函数。applycall都调用该函数。

bind()还允许向args数组添加其他参数。

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

简而言之,所有方法都用于在常规函数中显式设置上下文(this)

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

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

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

备注:

  1. 调用和应用都很相似,唯一的区别是他们期望参数的方式
  2. 上述方法不适用于箭头函数

JavaScript中call()、应用()和绑定()方法的第一个区别是它们的执行时间!调用()和应用()类似,会立即执行,而bind()会创建一个新函数,我们必须在以后的任何时间点显式调用它!

另一个区别是,在传递参数时,call()允许我们一个接一个地传递,用逗号分隔,应用()允许我们作为参数数组传递,而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);