gpt4 book ai didi

javascript - 绑定(bind)、应用和调用方法之间的区别?

转载 作者:可可西里 更新时间:2023-11-01 02:04:26 24 4
gpt4 key购买 nike

我在 stackoverflow 和网络上搜索,无法得到正确的结果或解释这三种方法之间的选址差异。

据我所知,它们都在不同的上下文中执行相同的函数/方法。

var google = {  
makeBeer : function(arg1,arg2){
alert([arg1, arg2]);
}
}

google.makeBeer('water','soda');

这是我的google对象的正常功能。现在,当我在这里使用 call 和 bind 方法时,这里是输出。

var google = {
makeBeer: function (arg1, arg2) {
alert([arg1, arg2]);
}
}

google.makeBeer('water', 'soda');

function yahoo() {}

var yah = new yahoo();
google.makeBeer.call(yah, 'pepsi', 'coke');

function msn() {

}

var msn = new msn();
google.makeBeer.call(msn, 'sprite', 'limca');

我仍然看不出这样做的目的,我可以继续使用不同的参数调用 google.makeBeer 三次。

谁能在这方面给我更多启发。

最佳答案

applycall 是一回事,除了一个以数组形式接受要传递给函数的参数,另一个以参数形式接受要传递给函数的参数。

bindcallapply 的作用相同,具体取决于您使用的框架,但不会立即调用该函数它返回一个新函数,您的参数绑定(bind)到 this 并且当从新范围或上下文调用该函数时,this 仍将保留您绑定(bind)到它的任何内容。绑定(bind)还允许您防止您的构造函数被 applycall “黑客攻击”,因为它始终使用 this 的绑定(bind)参数,无论某人发送的内容以尝试通过 callapply 覆盖 this

这是一个例子:

function Profile(u) {
this.user = u;
this.getUser = function () {
return this.user;
};
}

function Profile2(u) {
this.user = u;
this.getUser = (function () {
return this.user;
});
}

function Profile3(u) {
this.user = u;
this.getUser = (function () {
return this.user;
});
}

var x = new Profile('guest');
var x2 = new Profile2('guest');
var x3 = new Profile3('guest');

alert(x.getUser.apply({
user: 'Vinoth'
})); // Vinoth
alert(x2.getUser.call({
user: 'Babu'
})); // babu
alert(x3.getUser.bind(x3).call({
user: 'Nandan'
})); // Guest

关于javascript - 绑定(bind)、应用和调用方法之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15404493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com