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

Roy*_*mir 751 javascript arrays function

我已经知道apply并且call是类似的功能集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));
Run Code Online (Sandbox Code Playgroud)

jsbin

Cha*_*had 755

.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.
};
Run Code Online (Sandbox Code Playgroud)

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

一个简单,天真的bind实现就像:

Function.prototype.bind = function(ctx) {
    var fn = this;
    return function() {
        fn.apply(ctx, arguments);
    };
};
Run Code Online (Sandbox Code Playgroud)

还有更多内容(比如传递其他args),但您可以阅读更多相关信息并查看MDN上的实际实现.

希望这可以帮助.

  • 这正是`bind`返回的原因. (5认同)
  • 您还可以使用bind for partials,在调用函数之前传入参数. (4认同)
  • 您只是重新实现绑定,并没有真正的区别。不管怎样,你只是将它包装在一个闭包中,该闭包可以访问保存上下文的范围变量。你的代码基本上是我发布的polyfill。 (3认同)
  • @RoyiNamir这是正确的,您可以稍后使用返回的"绑定"函数,并保持上下文. (2认同)

Cur*_*ero 431

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

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"
Run Code Online (Sandbox Code Playgroud)

结合入功能和它需要被这样分开调用:

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"
Run Code Online (Sandbox Code Playgroud)

或者像这样:

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

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"                                     
Run Code Online (Sandbox Code Playgroud)

  • 您刚刚通过代码片段教了我有关函数内部使用的参数功能。建议提及“use strict”以避免覆盖此类保留关键字。+1。 (3认同)
  • 感谢您的改进建议。我稍微编辑了我的答案。@iono您的建议有一些不准确之处,因此无法批准它,但我自己在答案中进行了编辑。希望现在更加全面。 (3认同)
  • 这是否意味着区别在于 Bind 是一个闭包? (2认同)

Ami*_*hah 176

以简单形式回答

  • 调用调用该函数并允许您逐个传入参数.
  • Apply调用该函数并允许您将参数作为数组传递.
  • Bind返回一个新函数,允许您传入一个this数组和任意数量的参数.

应用与呼叫与绑定示例

呼叫

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
Run Code Online (Sandbox Code Playgroud)

应用

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
Run Code Online (Sandbox Code Playgroud)

捆绑

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
Run Code Online (Sandbox Code Playgroud)

何时使用每个

通话和申请是可以互换的.只需确定发送数组或逗号分隔的参数列表是否更容易.

我总是记得哪一个是记住Call是for逗号(分隔列表)和Apply是for Array.

绑定有点不同.它返回一个新函数.Call和Apply立即执行当前功能.

Bind非常适合很多事情.我们可以使用它来调整上面例子中的函数.我们可以使用一个简单的hello函数并将其转换为helloJon或helloKelly.我们也可以将它用于像onClick这样的事件,我们不知道什么时候它们会被解雇,但我们知道我们希望它们有什么背景.

全球化志愿服务青年:codeplanet.io

  • 很棒的答案,如果是我的问题帖子,我给你勾号. (7认同)
  • call = = comma,apply == array是一个很好的小记忆技巧 (4认同)
  • @DaryllSantos,根据 MDN:thisArg 可选。为调用函数提供的 this 值。请注意,这可能不是该方法看到的实际值:如果该方法是非严格模式下的函数,则 null 和 undefined 将被替换为全局对象,并且原始值将被转换为对象。所以如果你不在函数中使用它也没关系。 (2认同)

Fel*_*ing 69

我在函数对象,函数调用call/applybind前一阵子之间创建了这种比较:

在此处输入图片说明

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


jan*_*mon 52

它允许设置值,this而与调用函数的方式无关.这在使用回调时非常有用:

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

  var obj = {
     message : "hello"
  };
  setTimeout(sayHello.bind(obj), 1000);
Run Code Online (Sandbox Code Playgroud)

为了达到相同的结果,call看起来像这样:

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

  var obj = {
     message : "hello"
  };
  setTimeout(function(){sayHello.call(obj)}, 1000);
Run Code Online (Sandbox Code Playgroud)

  • 像你之前展示过的`.bind()`的用法是不正确的.当你使用`fn.bind(obj)时,将返回其他函数(不是你之前创建的).并且没有能力在`binded`函数内改变`this`的值.大多数情况下,这用于回调`this`保险.但在你的例子中 - 结果没有差异.但是`fn!== fn.bind(obj);`注意到. (5认同)
  • @InviS 我不明白你的评论 - 为什么没有不同? (2认同)
  • 通话和申请的区别在于.在调用中,您将参数作为逗号分隔的字符串传递,而在应用中,您可以以数组的形式传递参数.休息是一样的. (2认同)

tk1*_*404 44

假设我们有multiplication功能

function multiplication(a,b){
console.log(a*b);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

multiby2(3); //6
multiby2(4); //8
Run Code Online (Sandbox Code Playgroud)

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

var getSixAlways = multiplication.bind(this,3,2);
Run Code Online (Sandbox Code Playgroud)

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

getSixAlways();//6
Run Code Online (Sandbox Code Playgroud)

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

var magicMultiplication = multiplication.bind(this);
Run Code Online (Sandbox Code Playgroud)

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

哦不,我们将乘法功能隐藏在magicMultiplication中.

调用 magicMultiplication返回一个空白function b()

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

打电话和申请怎么样?

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

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

简单来说,bind创建函数,callapply执行函数,而apply期望数组中的参数

  • 解释得很好! (3认同)
  • +1"for simple words,`bind`创建函数,`call`和`apply`执行函数,而`apply`期望数组中的参数" (3认同)
  • 函数 b 是什么?为什么它是空白的? (3认同)
  • @DavidSpector,它不是函数b。它是一个采用名为“b”的参数的函数,因为函数“乘法”是如何使用“a”和“b”作为参数定义的。希望有帮助! (3认同)

Joh*_*ers 31

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

Function.prototype.bind()另一方面,创建一个具有给定this值的新函数,并返回该函数而不执行它.

那么,让我们看一个如下所示的函数:

var logProp = function(prop) {
    console.log(this[prop]);
};
Run Code Online (Sandbox Code Playgroud)

现在,让我们看一个看起来像这样的对象:

var Obj = {
    x : 5,
    y : 10
};
Run Code Online (Sandbox Code Playgroud)

我们可以将函数绑定到我们的对象,如下所示:

Obj.log = logProp.bind(Obj);
Run Code Online (Sandbox Code Playgroud)

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

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
Run Code Online (Sandbox Code Playgroud)

真正有趣的地方是,当你不仅绑定一个值this,而且还为它的参数绑定prop:

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
Run Code Online (Sandbox Code Playgroud)

我们现在可以这样做:

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
Run Code Online (Sandbox Code Playgroud)


Arh*_*ury 22

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

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

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

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

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

称呼

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

printFullName.call(name,"Mumbai","Taufa");     //Arham Chowdhury, Mumbai, Taufa
Run Code Online (Sandbox Code Playgroud)

申请

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

printFullName.apply(name, ["Mumbai","Taufa"]);     //Arham Chowdhury, Mumbai, Taufa
Run Code Online (Sandbox Code Playgroud)

绑定

bind 方法与 call 相同,除了 bind 返回一个可以稍后通过调用使用的函数(不会立即调用它)

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

printMyNAme();      //Arham Chowdhury, Mumbai, Taufa
Run Code Online (Sandbox Code Playgroud)

printMyNAme() 是调用函数的函数

下面是jsfiddle的链接

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

  • 这是一个很好的解释 (4认同)
  • 非常感谢这个很好的解释 (3认同)
  • 这很好解释。谢谢@ArhamChowdhury (3认同)
  • 如果我将数组传递给调用方法会发生什么?我检查过它工作正常。你能解释一下吗? (2认同)

小智 21

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

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

apply:它以提供的上下文和参数作为数组执行函数 .


zan*_*ngw 18

这是一篇很好的文章来说明它们之间的区别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?
    
    Run Code Online (Sandbox Code Playgroud)
  • 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?
    
    Run Code Online (Sandbox Code Playgroud)

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

  • 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 + ".";
        }
     }
    
    Run Code Online (Sandbox Code Playgroud)

    我们可以使用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."
    
    Run Code Online (Sandbox Code Playgroud)
  • apply()或者call()设置

    apply,callbind方法都是使用调用方法时设置这个值,他们这样做稍微不同的方式,让我们的JavaScript代码中使用直接控制和多功能性.

    设置此值时,applycall几乎相同,只是将函数参数apply ()作为数组传递,而必须单独列出参数以将它们传递给call ()方法.

    下面是一个使用call或在回调函数中apply设置它的示例.

    // 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
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用apply或借用函数call

    • 借用阵列方法

      让我们创建一个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?
      
      Run Code Online (Sandbox Code Playgroud)

      另一种常见情况是转换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"]
      
      Run Code Online (Sandbox Code Playgroud)
    • 借用其他方法

      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?
      
      Run Code Online (Sandbox Code Playgroud)
  • 使用apply()执行可变元数函数

Math.max是变量函数的一个例子,

// We can pass any number of arguments to the Math.max () method?
console.log (Math.max (23, 11, 34, 56)); // 56
Run Code Online (Sandbox Code Playgroud)

但是,如果我们有一系列数字要传递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
Run Code Online (Sandbox Code Playgroud)

这是该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
Run Code Online (Sandbox Code Playgroud)


Eld*_*bek 8

call/apply立即执行函数:

func.call(context, arguments);
func.apply(context, [argument1,argument2,..]);
Run Code Online (Sandbox Code Playgroud)

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

function bind(func, context) {
    return function() {
        return func.apply(context, arguments);
    };
}
Run Code Online (Sandbox Code Playgroud)


Shi*_*ljo 7

句法

  • 调用(thisArg, arg1, arg2, ...)
  • 应用(thisArg,argsArray)
  • 绑定(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
Run Code Online (Sandbox Code Playgroud)


Sag*_*jal 6

调用应用和绑定。以及它们有何不同。

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

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

让我们了解什么时候使用 call 和 apply 。让我们假设您是一名工程师并且您拥有your_scooteryour_car并且your_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);
Run Code Online (Sandbox Code Playgroud)

所以上面的例子成功地给 your_scooter, your_car, your_jet 一个来自汽车对象的特征。

让我们深入了解 这里我们将拆分上面的代码行。 automobile.push_button_engineStart正在帮助我们获得正在使用的方法。

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

现在 apply 和 call 接受两个参数。

  1. 语境
  2. 争论

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

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

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

什么是JS绑定函数?

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

让我们把前面的例子做得更好。之前我们使用了一个属于汽车对象的方法,并用它来装备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);
Run Code Online (Sandbox Code Playgroud)

还是不满意?

让我们用泪珠说清楚吧。实验的时间。我们将返回调用和应用函数应用程序并尝试存储函数的值作为参考。

下面的实验失败了,因为 call 和 apply 是立即调用的,因此,我们永远不会进入将引用存储在变量中的阶段,这是绑定函数窃取节目的地方

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


Shu*_*vro 6

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)
Run Code Online (Sandbox Code Playgroud)

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])
Run Code Online (Sandbox Code Playgroud)

**call 和 apply 函数是不同的,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()
Run Code Online (Sandbox Code Playgroud)


raj*_*oju 5

Call: 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
Run Code Online (Sandbox Code Playgroud)


小智 5

调用,应用和绑定之间的基本区别是:

如果您希望执行上下文出现在图片的后面,将使用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**
Run Code Online (Sandbox Code Playgroud)

假设我想在其他变量中使用此方法

var car1 = car.displayDetails('Nishant');
car1(); // undefined
Run Code Online (Sandbox Code Playgroud)

要在其他变量中使用car的引用,您应该使用

var car1 = car.displayDetails.bind(car, 'Nishant');
car1(); // Nishant this is your car 007 Mercedes
Run Code Online (Sandbox Code Playgroud)

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

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

func();
// Number: 1
Run Code Online (Sandbox Code Playgroud)

为什么?因为现在func与数字1绑定,如果在这种情况下不使用bind,它将指向全局对象。

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

func();
// Object
Run Code Online (Sandbox Code Playgroud)

当您想同时执行该语句时,将使用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 the array
displayDetails.call(Name, ['Nishant'])
// Nishant, this is your name: age25 workSSE
Run Code Online (Sandbox Code Playgroud)


小智 5

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"));
Run Code Online (Sandbox Code Playgroud)

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)); 
Run Code Online (Sandbox Code Playgroud)

绑定():--

       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));
Run Code Online (Sandbox Code Playgroud)