Javascript 调用()和应用()与绑定()?

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

提问人:Royi Namir 提问时间:3/17/2013 最后编辑:Tamir AbutbulRoyi Namir 更新时间:9/28/2023 访问量:581324

问:

我已经知道了,并且是设置(函数的上下文)的类似函数。applycallthis

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

问题:

但是我什么时候应该使用这个方法呢?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公司

JavaScript 数组 函数

评论

15赞 Gabriel Llamas 3/17/2013
如果有用户在发布答案或点赞之前查看 OP 的声誉点,这不是您的错:)
81赞 Nope 3/17/2013
调用和应用调用函数,而绑定创建函数。尽管您可以单独传递参数并作为参数数组传递参数。有关更多详细信息,请查看链接的文档,该文档应该能够完全回答您的问题。call()apply()
4赞 Nope 3/17/2013
kind of weird there is not an existing question about this :关于那个。这可能是因为在 JavaScript 1.8.5 - ECMA-262 第 5 版中已经存在其他两个之后添加的。虽然并且自 JavaScript 1.3 - ECMA-262 第 3 版以来一直存在。SO 对他们有疑问,例如:调用和申请之间的区别是什么。我只是猜测,因为我自己也在想。bind()call()apply()
0赞 Mahi 11/15/2016
你在这里需要这些方法(调用,应用,绑定)吗?如果没有这个,你也可以调用该方法,这将只指向对象
0赞 Praneet Dixit 8/3/2020
@Nope如果我是对的,就像. 创建一个新数组并创建一个新函数。我是吗?bindmapmapbind

答:

906赞 Chad 3/17/2013 #1

当您希望稍后在特定上下文中调用该函数时使用,这在事件中很有用。在要立即调用函数时使用 或,并修改上下文。.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 上的真实实现。

评论

3赞 Chad 3/17/2013
@RoyiNamir正确,则可以稍后使用返回的“bound”函数,并且上下文将被维护。
7赞 Chad 3/17/2013
这正是回报。bind
5赞 Andrew Kirkegaard 3/17/2013
还可以将 bind 用于分部,在调用函数之前传入参数。
3赞 Chad 10/6/2014
您只是在重新实现绑定,实际上并没有什么区别。无论哪种方式,您都只是将其包装在一个闭包中,该闭包可以访问保存上下文的范围变量。你的代码基本上是我发布的 polyfill。
1赞 Chad 9/3/2022
不,参数是函数中可用的特殊对象。参见:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
57赞 jantimon 3/17/2013 #2

它允许设置值,而与函数的调用方式无关。这在处理回调时非常有用: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);

评论

6赞 ValeriiVasin 3/17/2013
使用您之前显示的类似是不正确的。当您使用其他函数时,将返回(不是您之前创建的函数)。并且没有能力改变函数内部的值。这主要用于回调保险。但在您的示例中 - 结果没有差异。但请注意。.bind()fn.bind(obj)thisbindedthisfn !== fn.bind(obj);
2赞 jantimon 8/1/2015
@InviS我不明白你的评论——为什么没有不同?
3赞 Ashish Yadav 2/15/2017
调用和申请的区别在于。在 Call 中,您可以将参数作为逗号分隔的字符串传递,而在 Apply 中,您可以以数组的形式传递参数。其余的都是一样的。
0赞 Sudhansu Choudhary 9/24/2019
逗号分隔的字符串??只需将参数作为逗号分隔!!
83赞 tk120404 6/11/2015 #3

TL;博士:

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

完整解释

假设我们有函数multiplication

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

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

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

调用返回空白magicMultiplicationfunction b()

在执行时,它工作正常magicMultiplication(6,5); //30

打电话申请怎么样?

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

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

评论

3赞 CatalinBerta 12/19/2016
解释得很好!
11赞 Josh Buchea 7/8/2017
+1 表示“简单来说,创建函数并执行函数,同时期望数组中的参数”bindcallapplyapply
3赞 David Spector 6/1/2021
什么是函数 b,为什么它是空白的?
3赞 indieNik 8/7/2021
@DavidSpector,它不是函数 b。它是一个函数,它接受一个名为“b”的参数,因为函数“乘法”是如何用“a”和“b”作为参数定义的。希望对您有所帮助!
522赞 CuriousSuperhero 8/10/2015 #4

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

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"

applycall 类似,只是它采用一个类似数组的对象,而不是一次列出一个参数:

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"                                     

评论

2赞 Gregory R. 5/25/2016
这是否意味着 Bind 是闭包的区别?
3赞 RBT 6/17/2017
您刚刚通过代码片段向我介绍了函数内部使用的参数功能。建议提及以避免覆盖此类保留关键字。+1."use strict"
0赞 iono 6/30/2017
@Max同意了;我提交了一个编辑,其中“this”是错误的或没有意义,直到我们使用 bind/call/apply
3赞 CuriousSuperhero 6/30/2017
感谢您的改进建议。我稍微编辑了一下我的答案。@iono您的建议有一些不准确之处,因此无法批准,但对答案进行了自己的编辑。希望它现在更全面。
38赞 John Slegers 1/18/2016 #5

Function.prototype.call() 和 Function.prototype.apply() 都调用具有给定值的函数,并返回该函数的返回值。this

另一方面,Function.prototype.bind() 创建一个具有给定值的新函数,并在不执行的情况下返回该函数。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 : 5
Obj.log('y'); // Output : 10

真正有趣的是,当你不仅为 ,而且为 for 绑定一个值时,它的参数:thisprop

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

我们现在可以这样做:

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
21赞 zangw 4/8/2016 #6

这里有一篇很好的文章来说明两者之间的区别,并总结如下。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 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()允许我们借用方法

    // 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 对象可能已经有一个 属性或方法名称 。 我们不想意外地覆盖它。正如我们将在下面的讨论中看到的那样, 最好使用 OR 方法借用方法。showDatacarsshowDataApplyCallApplyCall

  • bind()允许我们调侃一个函数

    函数 Currying,也称为部分函数应用,是使用 函数(接受一个或多个参数),返回已设置某些参数的新函数。

    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()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()或设置call()

    、 和 方法都用于在调用方法时设置 this 值,并且它们只需稍微 允许在我们的 JavaScript 代码中使用直接控制和多功能性的不同方式。applycallbind

    设置 this 值时,和方法几乎相同,只是将函数参数作为数组传递给,而必须单独列出参数才能将它们传递给方法。applycallapply ()call ()

    下面是一个在回调函数中使用或设置参数的示例。callapply

    // 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
    
  • 使用 或 借用函数applycall

    • Borrow Array 方法

      让我们创建一个对象并借用一些数组方法来操作我们的数组类对象。array-like

      // 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"]
      
    • 借用其他方法

      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​
      
  • 用于执行变量函数apply()

Math.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
-1赞 Xin Tao 4/15/2016 #7

我认为它们的位置相同:它们都可以更改函数的这个值。它们的区别是:bind 函数将返回一个新函数作为结果;call 和 apply 方法将立即执行函数,但 apply 可以接受数组作为参数,并且它将解析分隔的数组。而且,绑定函数可以是 Currying。

3赞 oceanGermanique 8/20/2016 #8

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

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

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

bindHelper(arguments);
-3赞 user7339156 12/25/2016 #9

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

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 指的是窗口对象,所以我们需要使用 bind 将演示对象上下文传递给 this.getValue 函数。这意味着我们只传递带有演示对象上下文的函数,而不是实际调用函数。

希望你理解。

更多信息请参考 JavaScript 绑定函数 了解详情

11赞 Eldiyar Talantbek 2/8/2017 #10

call/apply 立即执行函数:

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

bind 不会立即执行函数,但返回包装的 apply 函数(供以后执行):

function bind(func, context) {
    return function() {
        return func.apply(context, arguments);
    };
}
9赞 Sagar Munjal 3/28/2017 #11

调用 apply 和 bind。以及它们有何不同。

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

你有三辆汽车,它们以相同的机制(方法)开始。 我们用方法创建了一个对象。your_scooter , your_car and your_jetautomobilepush_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");
    }
}

让我们了解何时使用调用和应用。假设您是一名工程师,并且您拥有 ,并且没有附带push_button_engine_start,并且您希望使用第三方。your_scooteryour_caryour_jetpush_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()

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

  1. 上下文
  2. 参数

因此,我们在这里在最后一行代码中设置上下文。

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

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

什么是JS Bind函数?

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

让我们把前面的例子做得更好。前面我们使用了属于汽车对象的方法,并用它来装备.现在让我们想象一下,我们想单独提供一个单独的汽车,以便在我们希望的执行的任何后期阶段单独启动我们的汽车。your_car, your_jet and your_scooterpush_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);

还是不满意?

让我们把它说清楚,就像泪珠一样。是时候进行实验了。我们将返回调用和应用函数 application,并尝试将函数的值存储为参考。

下面的实验失败了,因为 call 和 apply 是立即调用的,因此,我们永远不会进入将引用存储在变量中的阶段,这是 bind 函数抢尽风头的地方

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

9赞 Shiljo Paulson 6/16/2017 #12

语法

  • 调用(thisArg, arg1, arg2, ...)
  • apply(thisArg, argsArray)
  • bind(thisArg[, arg1[, arg2[, ...]]])

这里

  • 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

321赞 Amit Shah 10/12/2017 #13

以最简单的形式回答

  • 调用调用该函数,并允许您通过以下方式传入参数 一。
  • Apply 调用该函数并允许您传入参数 作为数组。
  • Bind 返回一个新函数,允许您传入 此数组和任意数量的参数。

应用、调用和绑定示例

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

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 是数组。

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

Bind 在很多方面都很棒。我们可以用它来编译函数,如上面的例子所示。我们可以采用一个简单的 hello 函数,并将其转换为 helloJon 或 helloKelly。我们也可以将它用于像 onClick 这样的事件,我们不知道它们何时会被触发,但我们知道我们希望它们具有什么上下文。

参考: codeplanet.io

评论

0赞 Daryll Santos 5/17/2018
在 和 中,是否意味着如果您没有内部方法,那么您将第一个参数分配为 ?callapplythisnull
2赞 Amit Shah 5/19/2018
@DaryllSantos,根据 mdn:thisArg 可选。为调用函数提供的 this 值。请注意,这可能不是该方法看到的实际值:如果该方法是非严格模式下的函数,则 null 和 undefined 将被替换为全局对象,并且原始值将被转换为对象。因此,如果您不在函数中使用它,则无关紧要。
20赞 drlff 6/9/2018
调用 = = 逗号,应用 == 数组是一个很好的小记忆技巧
0赞 Pratik Joshi 8/3/2018
var person1 = {firstName: 'Jon', lastName: 'Kuperman'}; function say(greeting) { console.log(greeting + ' ' + this.firstName + ' ' + this.lastName); } say.apply(person1, ['Hello']); // Hello Jon Kuperman工作正常并输出 VM128:4 你好乔恩·库珀曼
28赞 Siddhartha 11/23/2017 #14

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

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

apply:它以数组的形式使用提供的上下文和参数执行函数。

评论

0赞 Mohammed H 6/28/2018
简单而谦逊!
3赞 pandhari 12/15/2017 #15
    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;
271赞 Felix Kling 2/7/2019 #16

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

enter image description here

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

5赞 raju poloju 2/7/2019 #17

调用:调用调用函数,并允许您逐个传递参数

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

捆: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

12赞 Nishant Parashar 8/10/2019 #18

Call、Apply 和 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

我们来谈谈绑定函数的更广泛使用

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
5赞 Raushan 12/22/2019 #19

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));
6赞 Shuvro 3/14/2020 #20

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 apply()

    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 函数是区别 call take separate 参数,但 apply take 数组 喜欢:[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()
44赞 Arham Chowdhry 5/28/2020 #21

所有这些方法背后的主要概念是函数借用

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

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

以下是所有这些方法的示例:

let name = {
    firstName: "Arham",
    lastName: "Chowdhury",
}

printFullName = function(hometown, company) {
    console.log(`${this.firstName} ${this.lastName}, ${hometown}, ${company}`);
}

CALL

第一个参数,例如调用方法中的名称始终是对(this)变量的引用,后一个参数将是函数变量:

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

APPLY

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()是调用该函数的函数。

Codepen.io 上的游乐场

评论

4赞 Mir Stephen 7/26/2020
这是一个很好的解释
0赞 Arham Chowdhry 8/10/2020
谢谢@DarioushPD
3赞 Hamid 11/16/2020
非常感谢这个很好的解释
3赞 Raheem Mohamed 12/5/2020
这很好解释。谢谢@ArhamChowdhury
2赞 Vasanth 1/1/2021
如果我将数组传递给调用方法会发生什么?当我检查它时,它工作正常。你能解释一下吗?
2赞 mster 8/13/2020 #22

将来使用 bind 调用函数。和调用函数。applycall

bind()还允许将其他参数附加到 args 数组中。

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

0赞 Mukesh Bhati 2/5/2022 #23

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

调用:调用在给定的上下文中调用函数,并允许逐个传递参数

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

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

笔记:

  1. Call 和 Apply 两者相似,唯一的区别是它们期望参数的方式
  2. 上述方法不适用于箭头函数
0赞 Brothers Gaming Xtreme 7/3/2022 #24

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