var Button = function(content) {
this.content = content;
};
Button.prototype.click = function() {
console.log(this.content + ' clicked');
};
var myButton = new Button('OK');
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the global object
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
打印出来:
OK clicked
undefined clicked
OK clicked
您还可以在第一个( this )参数之后添加额外参数,并且 bind 将这些值传递给原始函数 . 您稍后传递给绑定函数的任何其他参数将在绑定参数之后传入:
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
Button.prototype.hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
};
要么:
Button.prototype.hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
要么:
Button.prototype.hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
function getMonthlyFee(fee){
var remaining = this.total - fee;
this.total = remaining;
return this.name +' remaining balance:'+remaining;
}
现在,您希望将此功能重新用于其他俱乐部会员 . 请注意,每月费用因会员而异 .
让我们假设雷切尔的余额为500,每月会员费为90 .
var rachel = {name:'Rachel Green', total:500};
现在,创建一个可以反复使用的功能,每月从她的帐户中扣除费用
//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320
var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200
7
bind() 的最简单用法是创建一个函数,无论它如何调用,都使用特定的 this 值调用 .
x = 9;
var module = {
x: 81,
getX: function () {
return this.x;
}
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
例: -
var checkRange = function(value){
if(typeof value !== "number"){
return false;
}
else {
return value >= this.minimum && value <= this.maximum;
}
}
var range = {minimum:10,maximum:20};
var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
var result = boundedFunc(15); //passing value
console.log(result) // will give true;
11
bind()方法创建一个新的函数实例,该值绑定到传递给bind()的值 . 例如:
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue
var x = 9; // this refers to global "window" object here in the browser
var person = {
x: 81,
getX: function() { return this.x; }
};
var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).
document.getElementById("demo1").innerHTML = y();
document.getElementById("demo2").innerHTML = x2();
bind() 方法将对象作为第一个参数并创建一个新函数 . 调用函数时,函数体中 this 的值将是作为 bind() 函数中的参数传入的对象 .
无论如何,这在JS中是如何工作的
javascript中 this 的值依赖于函数调用的对象 . The value of this always refers to the object left of the dot from where is the function is called . 在全局范围的情况下,这是 window (或 nodeJS 中的 global ) . 只有 call , apply 和 bind 才能以不同方式更改此绑定 . 下面是一个示例,说明this关键字的工作原理:
let obj = {
prop1: 1,
func: function () { console.log(this); }
}
obj.func(); // obj left of the dot so this refers to obj
const customFunc = obj.func; // we store the function in the customFunc obj
customFunc(); // now the object left of the dot is window,
// customFunc() is shorthand for window.customFunc()
// Therefore window will be logged
如何使用绑定?
绑定可以通过使用 this 将引用的固定对象来帮助克服 this 关键字的困难 . 例如:
var name = 'globalName';
const obj = {
name: 'myName',
sayName: function () { console.log(this.name);}
}
const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred
say(); // now because this function is executed in global scope this will refer to the global var
const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object
boundSay(); // Now this will refer to the name in the obj object: 'myName'
一旦函数绑定到特定的 this 值,我们就可以传递它,甚至将它放在其他对象的属性上 . this 的值将保持不变 .
9
如上所述, Function.bind() 允许您指定函数将执行的上下文(也就是说,它允许您传递 this 关键字将在函数体中解析的对象 .
/**
* Bind is a method inherited from Function.prototype same like call and apply
* It basically helps to bind a function to an object's context during initialisation
*
* */
window.myname = "Jineesh";
var foo = function(){
return this.myname;
};
//IE < 8 has issues with this, supported in ecmascript 5
var obj = {
myname : "John",
fn:foo.bind(window)// binds to window object
};
console.log( obj.fn() ); // Returns Jineesh
7
bind函数使用与它调用的函数相同的函数体创建一个新函数 . 它使用this参数调用 . 为什么我们使用bind fun . :当每次创建一个新实例并且我们必须使用第一个初始实例时,我们使用bind fun.We不能覆盖绑定fun.simply它存储类的初始对象 .
var rateOfInterest='4%';
var axisBank=
{
rateOfInterest:'10%',
getRateOfInterest:function()
{
return this.rateOfInterest;
}
}
axisBank.getRateOfInterest() //'10%'
let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax
knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context
let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank); //so here we need bind function call to its local context
knowExactAxisBankInterest() // '10%'
13 回答
Bind创建一个新函数,将
this
设置为传递给bind()
的第一个参数 .这是一个示例,演示如何使用
bind
传递具有正确this
的成员方法:打印出来:
您还可以在第一个(
this
)参数之后添加额外参数,并且bind
将这些值传递给原始函数 . 您稍后传递给绑定函数的任何其他参数将在绑定参数之后传入:打印出来:
有关更多信息和交互式示例,请查看JavaScript Function bind .
更新:ECMAScript 2015增加了对
=>
功能的支持 .=>
函数更紧凑,不会将this
指针从其定义范围更改,因此您可能不需要经常使用bind()
. 例如,如果您希望第一个示例中的Button
上的函数将click
回调连接到DOM事件,则以下是执行此操作的所有有效方法:要么:
要么:
bind允许 -
将"this"的值设置为特定对象 . 这变得非常有用,因为有时this不是预期的 .
重用方法
咖喱一个功能
例如,您可以扣除每月的俱乐部费用
现在,您希望将此功能重新用于其他俱乐部会员 . 请注意,每月费用因会员而异 .
让我们假设雷切尔的余额为500,每月会员费为90 .
现在,创建一个可以反复使用的功能,每月从她的帐户中扣除费用
现在,相同的getMonthlyFee函数可以用于具有不同会员费的另一个成员 . 例如,Ross Geller的余额为250,月费为25
bind()
的最简单用法是创建一个函数,无论它如何调用,都使用特定的this
值调用 .有关更多信息,请参阅此链接
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
从the MDN docs开始
Function.prototype.bind()
:那是什么意思?!
好吧,让我们看一个如下所示的函数:
现在,让我们看一个看起来像这样的对象:
我们可以将函数绑定到我们的对象,如下所示:
现在,我们可以在代码中的任何位置运行
Obj.log
:这是有效的,因为我们将
this
的值绑定到我们的对象Obj
.真正有趣的地方是,当你不仅为
this
绑定一个值,而且还为它的参数prop
绑定:我们现在可以这样做:
与
Obj.log
不同,我们不必传递x
或y
,因为我们在进行绑定时传递了这些值 .我将在理论上和实践上解释绑定
在javascript中绑定是一个方法 - Function.prototype.bind . bind是一种方法 . 它被称为函数原型 . 此方法创建一个函数,其主体类似于调用它的函数,但'this'指的是传递给bind方法的第一个参数 . 它的语法是
例: -
bind()方法创建一个新的函数实例,该值绑定到传递给bind()的值 . 例如:
这里,通过调用bind()并传入对象o,从sayColor()创建一个名为objectSayColor()的新函数 . objectSayColor()函数具有等于o的this值,因此即使作为全局调用,调用该函数也会导致显示字符串“blue” .
参考:Nicholas C. Zakas - 面向WEB开发人员的专业JAVASCRIPT®
变量具有本地和全球范围 . 假设我们有两个具有相同名称的变量 . 一个是全局定义的,另一个是在函数闭包内定义的,我们想要得到函数闭包内的变量值 . 在这种情况下,我们使用这个bind()方法 . 请看下面的简单示例:
通过将参数绑定到值来创建新函数
bind
方法从中创建一个新函数另一个函数,其中一个或多个参数绑定到特定值,包括隐式this
参数 .部分申请
这是partial application的一个例子 . 通常我们提供一个函数及其所有参数,它们产生一个值 . 这称为功能应用程序 . 我们将函数应用于它的参数 .
高阶函数(HOF)
部分应用程序是higher order function(HOF)的示例,因为它产生具有较少参数的新函数 .
绑定多个参数
您可以使用
bind
将具有多个参数的函数转换为新函数 .从实例方法转换为静态函数
在最常见的用例中,当使用一个参数调用时,
bind
方法将创建一个将this
值绑定到特定值的新函数 . 实际上,这会将实例方法转换为静态方法 .实现有状态回调
以下示例显示如何使用
this
的绑定可以使对象方法充当可以轻松更新对象状态的回调 .摘要:
bind()
方法将对象作为第一个参数并创建一个新函数 . 调用函数时,函数体中this
的值将是作为bind()
函数中的参数传入的对象 .无论如何,这在JS中是如何工作的
javascript中
this
的值依赖于函数调用的对象 . The value of this always refers to the object left of the dot from where is the function is called . 在全局范围的情况下,这是window
(或nodeJS
中的global
) . 只有call
,apply
和bind
才能以不同方式更改此绑定 . 下面是一个示例,说明this关键字的工作原理:如何使用绑定?
绑定可以通过使用
this
将引用的固定对象来帮助克服this
关键字的困难 . 例如:一旦函数绑定到特定的
this
值,我们就可以传递它,甚至将它放在其他对象的属性上 .this
的值将保持不变 .如上所述,
Function.bind()
允许您指定函数将执行的上下文(也就是说,它允许您传递this
关键字将在函数体中解析的对象 .一些执行类似服务的类似工具包API方法:
jQuery.proxy()
Dojo.hitch()
bind函数使用与它调用的函数相同的函数体创建一个新函数 . 它使用this参数调用 . 为什么我们使用bind fun . :当每次创建一个新实例并且我们必须使用第一个初始实例时,我们使用bind fun.We不能覆盖绑定fun.simply它存储类的初始对象 .
bind是一个在java脚本原型中可用的函数,因为名称建议bind用于将函数调用绑定到您正在处理的上下文中,例如: