提问人:Royi Namir 提问时间:3/17/2013 最后编辑:Tamir AbutbulRoyi Namir 更新时间:9/28/2023 访问量:581324
Javascript 调用()和应用()与绑定()?
Javascript call() & apply() vs bind()?
问:
我已经知道了,并且是设置(函数的上下文)的类似函数。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));
答:
当您希望稍后在特定上下文中调用该函数时使用,这在事件中很有用。在要立即调用函数时使用 或,并修改上下文。.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 上的真实实现。
评论
bind
它允许设置值,而与函数的调用方式无关。这在处理回调时非常有用: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()
fn.bind(obj)
this
binded
this
fn !== fn.bind(obj);
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 中。
调用返回空白magicMultiplication
function b()
在执行时,它工作正常magicMultiplication(6,5); //30
打电话申请怎么样?
magicMultiplication.call(this,3,2); //6
magicMultiplication.apply(this,[5,2]); //10
评论
bind
call
apply
apply
它们都将其附加到函数(或对象)中,区别在于函数调用(见下文)。
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"
评论
"use strict"
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 绑定一个值时,它的参数: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()
允许我们轻松设置在调用函数或方法时将绑定到哪个特定对象。// 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 方法借用方法。
showData
cars
showData
Apply
Call
Apply
Call
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 代码中使用直接控制和多功能性的不同方式。
apply
call
bind
设置 this 值时,和方法几乎相同,只是将函数参数作为数组传递给,而必须单独列出参数才能将它们传递给方法。
apply
call
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
使用 或 借用函数
apply
call
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
我认为它们的位置相同:它们都可以更改函数的这个值。它们的区别是:bind 函数将返回一个新函数作为结果;call 和 apply 方法将立即执行函数,但 apply 可以接受数组作为参数,并且它将解析分隔的数组。而且,绑定函数可以是 Currying。
想象一下,绑定不可用。 您可以按如下方式轻松构建它:
var someFunction=...
var objToBind=....
var bindHelper = function (someFunction, objToBind) {
return function() {
someFunction.apply( objToBind, arguments );
};
}
bindHelper(arguments);
当我们想为一个具有特定上下文的函数分配一个函数时,应该使用绑定函数。
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 绑定函数 了解详情
call/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。以及它们有何不同。
让我们学习、调用和应用任何日常术语。
你有三辆汽车,它们以相同的机制(方法)开始。
我们用方法创建了一个对象。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");
}
}
让我们了解何时使用调用和应用。假设您是一名工程师,并且您拥有 ,并且没有附带push_button_engine_start,并且您希望使用第三方。your_scooter
your_car
your_jet
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()
现在应用并调用接受两个参数。
- 上下文
- 参数
因此,我们在这里在最后一行代码中设置上下文。
automobile.push_button_engineStart.apply(your_scooter,[20])
call 和 apply 之间的区别在于 apply 接受数组形式的参数,而 call 可以接受逗号分隔的参数列表。
什么是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);
还是不满意?
让我们把它说清楚,就像泪珠一样。是时候进行实验了。我们将返回调用和应用函数 application,并尝试将函数的值存储为参考。
下面的实验失败了,因为 call 和 apply 是立即调用的,因此,我们永远不会进入将引用存储在变量中的阶段,这是 bind 函数抢尽风头的地方
var test_function = automobile.push_button_engineStart.apply(your_scooter);
语法
- 调用(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
以最简单的形式回答
- 调用调用该函数,并允许您通过以下方式传入参数 一。
- 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
评论
call
apply
this
null
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 你好乔恩·库珀曼
bind:它将函数与提供的值和上下文绑定,但不执行函数。要执行函数,您需要调用该函数。
call:它使用提供的上下文和参数执行函数。
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
调用:调用调用函数,并允许您逐个传递参数
应用: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
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
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 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()
所有这些方法背后的主要概念是函数借用。
函数借用允许我们在另一个对象上使用一个对象的方法,而不必复制该方法并将其维护在两个不同的地方。它是通过使用 、 或 来实现的,所有这些方法都是为了在我们借用的方法上显式设置它。.call()
.apply()
.bind()
Call
立即调用该函数,并允许您逐个传入参数。Apply
立即调用该函数,并允许将参数作为数组传入。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 上的游乐场。
评论
将来使用 bind 调用函数。和调用函数。apply
call
bind()
还允许将其他参数附加到 args 数组中。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
简单来说,所有方法都用于在常规函数中显式设置 context(this)
调用:调用在给定的上下文中调用函数,并允许逐个传递参数
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);
评论
call()
apply()
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()
bind
map
map
bind