bind()在JavaScript中的用途是什么?
当前回答
摘要:
bind()方法将对象作为第一个参数,并创建一个新函数。当调用函数时,函数体中this的值将是在bind()函数中作为参数传入的对象。
这在JS中是如何工作的
javascript中this的值始终取决于调用函数的对象。此值始终指调用函数的点左侧的对象。对于全局范围,这是窗口(或nodeJS中的全局)。只有调用、应用和绑定才能以不同方式更改此绑定。下面是一个示例,说明this关键字的工作原理:
让obj={prop1:1,func:function(){console.log(this);}}obj.func();//obj位于点的左侧,因此这是指obj常量customFunc=obj.func;//我们将函数存储在customFunc对象中customFunc();//现在点左边的对象是窗口,//customFunc()是window.customFunc(//因此,将记录窗口
如何使用绑定?
Bind可以帮助克服使用此关键字时遇到的困难,方法是在此处指定一个固定的对象。例如:
var name='globalName';常量对象={name:'myName',sayName:function(){console.log(this.name);}}常量say=obj.sayName;//我们只是存储函数,它的值不会被神奇地传递say();//现在,由于此函数在全局范围内执行,因此将引用全局变量const-boundSay=obj.sayName.bind(obj);//现在,this的值被绑定到obj对象bounday();//现在,这将引用obj对象中的名称:“myName”
一旦函数被绑定到特定的这个值,我们就可以传递它,甚至可以将它放到其他对象的财产中。其价值将保持不变。
其他回答
bind()的最简单用法是生成一个函数,无论它是如何被调用的。
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
有关详细信息,请参阅MDN Web Docs上的此链接:
函数.product.bind()
Bind创建一个新函数,该函数将强制函数内部的this作为传递给Bind()的参数。
下面是一个示例,展示了如何使用bind传递具有正确this的成员方法:
var myButton = {
content: 'OK',
click() {
console.log(this.content + ' clicked');
}
};
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis
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));
打印结果:
15
查看JavaScript函数绑定以获取更多信息和交互式示例。
更新:ECMAScript 2015增加了对=>函数的支持。=>函数更紧凑,不会从其定义范围更改this指针,因此您可能不需要经常使用bind()。例如,如果您希望第一个示例中Button上的一个函数将单击回调连接到DOM事件,以下都是实现这一点的有效方法:
var myButton = {
... // As above
hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
}
};
Or:
var myButton = {
... // As above
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() });
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
};
变量具有局部和全局作用域。假设我们有两个同名的变量。一个是全局定义的,另一个是在函数闭包内定义的,我们希望得到函数闭包内的变量值。在这种情况下,我们使用这个bind()方法。请参见下面的简单示例:
变量x=9;//这是指浏览器中的全局“窗口”对象var人={x: 81中,getX:函数(){返回此.x;}};var y=person.getX;//它将返回9,因为它将调用x的全局值(varx=9)。var x2=y.bind(人);//它将返回81,因为它将调用在名为person(x=81)的对象中定义的x的局部值。document.getElementById(“demo1”).innerHTML=y();document.getElementById(“demo2”).innerHTML=x2();<p id=“demo1”>0</p><p id=“demo2”>0</p>
考虑下面列出的简单程序,
//we create object user
let User = { name: 'Justin' };
//a Hello Function is created to Alert the object User
function Hello() {
alert(this.name);
}
//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();
//we create an instance to refer the this keyword (this.name);
bind函数创建了一个新函数,其函数体和它所调用的函数相同。它是用这个参数调用的。为什么我们使用bind fun?:当每次创建一个新实例时,我们必须使用第一个初始实例,然后使用bind fun。我们不能重写bind fun.暗示它存储类的初始对象。
setInterval(this.animate_to.bind(this), 1000/this.difference);
推荐文章
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?