定义:把函数拷贝一份(不是临时的),并插入到对象作用域上面,返回一个函数指针
<script>
function add(){
return this.x + this.y;
}
var obj = {
x:1,
y:2
}
console.log('bind前:',obj);
obj.e = add.bind(obj)
console.log('bind后:',obj);
console.log('执行obj.e():',obj.e());
</script>
效果:
<script>
function add(a,b){
return this.x * a + this.y * b;
}
var obj = {
x:1,
y:2
}
// console.log('bind前:',obj);
obj.e = add.bind(obj,10,100)
// console.log('bind后:',obj);
console.log('执行obj.e():',obj.e());
</script>
运行效果:
也可以bind时传部分参数,obj.e()执行时传剩下的参数,传递的顺序是形参的顺序
<script>
function add(a,b,c){
return this.x * a + this.y * b + c;
}
var obj = {
x:1,
y:2
}
obj.e = add.bind(obj,10,100)//指定前两个参数,10传给a,100传给b
console.log('执行obj.e():',obj.e(1));//传入最后一个参数c
</script>
bind时传入的参数不可修改:
obj.e = add.bind(obj,10,100);
相当于设置默认值a=10,b=100;在obj.e()
执行时不能修改;
如果bind时只设定了前部分参数,即a:add.bind(obj,10)
,在执行时设置后部分参数,即b:obj.e(100);
,这种情况下b的值可以被修改,a不能
<script>
//第一部分
function add(a,b){
return this.x * a + this.y * b;
}
var obj = {
x:1,
y:2
}
// console.log('bind前:',obj);
obj.e = add.bind(obj,10,100)
// console.log('bind后:',obj);
console.log('执行obj.e():',obj.e());
console.log('执行obj.e():',obj.e(10,10));
//第二部分
var x = 10;
var y = 20;
function add(a,b){
return this.x * a + this.y * b;
}
var obj1 = {
x:1,
y:2,
}
var obj2 = {
x:5,
y:6,
}
console.log('add:' + add(10,10));
console.log('add obj1:' + add.bind(obj1,20)(10));
obj2.e = add.bind(obj2,20,30);
console.log('add1 obj2:'+obj2.e());
console.log('add2 obj2:'+obj2.e(100,300));
</script>
运行结果:
前面两行是第一部分的打印结果,可以看到,执行时改变了a和b的值,但没有改变结果,因为a和b在bind时已经被指定
后面几行是第二部分的打印结果:
300是add(10,10)
的运行结果,因为在大环境下定义了x和y,add函数直接调用时,this是指向window的,所以:this.x * a + this.y * b = 10 * 10 + 20 *10 = 300;
40是add.bind(obj1,20)(10)
的运行结果,bind时指定a=20,执行时将10赋给b,所以this.x * a + this.y * b = 1 * 20 + 2 * 10 = 40;
后面的280都是obj2的计算,因为obj2在bind时已经指定a和b的值,执行时对a和b的修改不生效,所以都是this.x * a + this.y * b = 5 * 20 + 6 * 30 = 280