bind()在JavaScript中的用途是什么?
当前回答
变量具有局部和全局作用域。假设我们有两个同名的变量。一个是全局定义的,另一个是在函数闭包内定义的,我们希望得到函数闭包内的变量值。在这种情况下,我们使用这个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>
其他回答
如上所述,Function.bind()允许您指定函数将在其中执行的上下文(也就是说,它允许您传递this关键字将解析到函数体中的对象)。
执行类似服务的两个类似工具包API方法:
jQuery.proxy()
Dojo.hhitch()
我没有读过上面的代码,但我学到了一些简单的东西,所以我想在这里分享一下bind方法,我们可以将它用作任何普通方法。
<pre> note: do not use arrow function it will show error undefined </pre>
让solarSystem={太阳:“红色”,moon:“白色”,sunmoon:函数(){let dayNight=this.sun+'是太阳的颜色,在白天呈现,'+this.moon+'是月亮的颜色,晚上呈现';返回日夜间;}}让工作=功能(工作,睡眠){console.log(this.sunmoon());//访问solatSystem直到现在都显示错误undefine suncommon,因为我们无法直接访问我们使用的.bind()console.log('我在'+work+'中工作,在'+sleep中睡眠);}let outPut=work.bind(solarSystem);outPut(“日”,“夜”)
简单解释:
bind()创建一个新函数,即它返回给您的函数的新引用。
在该关键字后面的parameter中,传递要预配置的参数。实际上,它不会立即执行,只是准备执行。
您可以根据需要预配置任意多个参数。
理解绑定的简单示例:
function calculate(operation) {
if (operation === 'ADD') {
alert('The Operation is Addition');
} else if (operation === 'SUBTRACT') {
alert('The Operation is Subtraction');
}
}
addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
另一种用法是,可以将绑定函数作为参数传递给在另一个执行上下文下运行的另一个函数。
var name = "sample";
function sample(){
console.log(this.name);
}
var cb = sample.bind(this);
function somefunction(cb){
//other code
cb();
}
somefunction.call({}, cb);
考虑下面列出的简单程序,
//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);
推荐文章
- 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)之间的区别是什么?