nkr*_*ron 553
Bind创建一个新函数,该函数将this
设置为传递给的第一个参数bind()
.
这是一个示例,显示如何使用bind
传递成员方法具有正确的成员方法this
:
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
Run Code Online (Sandbox Code Playgroud)
打印出来:
OK clicked
undefined clicked
OK clicked
Run Code Online (Sandbox Code Playgroud)
您还可以在1st(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));
Run Code Online (Sandbox Code Playgroud)
打印出来:
15
Run Code Online (Sandbox Code Playgroud)
查看JavaScript函数绑定以获取更多信息和交互式示例.
更新:ECMAScript 2015增加了对=>
功能的支持. =>
函数更紧凑,不会将this
指针从其定义范围更改,因此您可能不需要bind()
经常使用.例如,如果您希望Button
第一个示例中的函数将click
回调挂钩到DOM事件,则以下是执行此操作的所有有效方法:
Button.prototype.hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
};
Run Code Online (Sandbox Code Playgroud)
要么:
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() });
}
Run Code Online (Sandbox Code Playgroud)
要么:
Button.prototype.hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
Run Code Online (Sandbox Code Playgroud)
Ren*_*M G 214
最简单的用法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
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅此链接
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Jha*_*bub 166
绑定允许 -
例如,您可以扣除每月的俱乐部费用
function getMonthlyFee(fee){
var remaining = this.total - fee;
this.total = remaining;
return this.name +' remaining balance:'+remaining;
}
Run Code Online (Sandbox Code Playgroud)
现在,您希望将此功能重新用于其他俱乐部会员.请注意,每月费用因会员而异.
让我们假设雷切尔的余额为500,每月会员费为90.
var rachel = {name:'Rachel Green', total:500};
Run Code Online (Sandbox Code Playgroud)
现在,创建一个可以反复使用的功能,每月从她的帐户中扣除费用
//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320
Run Code Online (Sandbox Code Playgroud)
现在,相同的getMonthlyFee函数可以用于具有不同会员费的另一个成员.例如,Ross Geller的余额为250,月费为25
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
Run Code Online (Sandbox Code Playgroud)
Joh*_*ers 72
从该MDN文档上Function.prototype.bind()
:
的绑定()方法创建一个新的功能,调用它时,具有其将此关键字设置为所提供的值,与前述的当新功能被调用任何设置参数给定的序列.
那是什么意思?!
好吧,让我们看一个如下所示的函数:
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
了对象的值Obj
.
真正有趣的地方是,当你不仅绑定一个值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)
与之不同Obj.log
,我们不必传递x
或者y
,因为我们在进行绑定时传递了这些值.
小智 19
变量具有本地和全球范围.假设我们有两个具有相同名称的变量.一个是全局定义的,另一个是在函数闭包内定义的,我们想要得到函数闭包内的变量值.在这种情况下,我们使用这个bind()方法.请看下面的简单示例:
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();
Run Code Online (Sandbox Code Playgroud)
<p id="demo1">0</p>
<p id="demo2">0</p>
Run Code Online (Sandbox Code Playgroud)
Wil*_*een 15
该bind()
方法将对象作为第一个参数并创建一个新函数.调用函数this
时,函数体中的值将是作为函数中的参数传入的对象bind()
.
this
无论如何,在JS中如何工作this
javascript中的值依赖于取决于调用函数的Object.它的值总是指点的左边的对象,调用函数的位置.在全球范围内的情况下,这是window
(或global
中nodeJS
).只有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
Run Code Online (Sandbox Code Playgroud)
绑定可以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'
Run Code Online (Sandbox Code Playgroud)
一旦函数绑定到特定this
值,我们就可以传递它,甚至将它放在其他对象的属性上.价值this
将保持不变.
小智 12
我将在理论上和实践上解释绑定
在javascript中绑定是一个方法 - Function.prototype.bind.bind是一种方法.它被称为函数原型.此方法创建一个函数,其主体类似于调用它的函数,但'this'指的是传递给bind方法的第一个参数.它的语法是
var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
Run Code Online (Sandbox Code Playgroud)
例: -
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;
Run Code Online (Sandbox Code Playgroud)
Ott*_*tti 10
bind()方法创建一个新的函数实例,该值绑定到传递给bind()的值.例如:
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue
Run Code Online (Sandbox Code Playgroud)
这里,通过调用bind()并传入对象o,从sayColor()创建一个名为objectSayColor()的新函数.objectSayColor()函数具有等于o的this值,因此即使作为全局调用,调用该函数也会导致显示字符串"blue".
参考:Nicholas C. Zakas - 面向WEB开发人员的专业JAVASCRIPT®
该bind
方法从另一个函数创建一个新函数,其中一个或多个参数绑定到特定值,包括隐式this
参数.
这是部分应用的示例.通常我们提供一个函数及其所有参数,它们产生一个值.这称为功能应用程序.我们将函数应用于它的参数.
部分应用程序是高阶函数(HOF)的一个示例,因为它产生具有较少数量参数的新函数.
您可以使用bind
将具有多个参数的函数转换为新函数.
function multiply(x, y) {
return x * y;
}
let multiplyBy10 = multiply.bind(null, 10);
console.log(multiplyBy10(5));
Run Code Online (Sandbox Code Playgroud)
在最常见的用例中,当使用一个参数调用时,该bind
方法将创建一个具有this
绑定到特定值的值的新函数.实际上,这会将实例方法转换为静态方法.
function Multiplier(factor) {
this.factor = factor;
}
Multiplier.prototype.multiply = function(x) {
return this.factor * x;
}
function ApplyFunction(func, value) {
return func(value);
}
var mul = new Multiplier(5);
// Produces garbage (NaN) because multiplying "undefined" by 10
console.log(ApplyFunction(mul.multiply, 10));
// Produces expected result: 50
console.log(ApplyFunction(mul.multiply.bind(mul), 10));
Run Code Online (Sandbox Code Playgroud)
以下示例显示了如何使用绑定this
使对象方法充当可以轻松更新对象状态的回调.
function ButtonPressedLogger()
{
this.count = 0;
this.onPressed = function() {
this.count++;
console.log("pressed a button " + this.count + " times");
}
for (let d of document.getElementsByTagName("button"))
d.onclick = this.onPressed.bind(this);
}
new ButtonPressedLogger();
Run Code Online (Sandbox Code Playgroud)
<button>press me</button>
<button>no press me</button>
Run Code Online (Sandbox Code Playgroud)
如上所述,Function.bind()
允许您指定函数将在其中执行的上下文(也就是说,它允许您传递this
关键字将在函数体中解析的对象.
一些执行类似服务的类似工具包API方法: