实例一:
var adc="dema";
function show(a,b){
console.log(this.adc,a,b);
}
// show();
var bch={
adc:"hb"
}
// show.apply(bch);
// show.call(bch); 只能借用方法但不创建自己的方法
var myShow =show.bind(bch,"sh","ap");
myShow();
实例二:
//单对象编程(this始终保持不变)
var list={
init:function() {
this.my="hanbing";
this.elem=document.getElementsByClassName("but")[0];
this.bindEvent();
},
bindEvent:function() {
this.elem.onclick=this.showMessage.bind(this,"wu",21);
},
showMessage:function(name,age,e) {
//参数从bind的实参参数从第二位左往右
console.log(this,name,age,e);//。。。 ‘wu’ 21 Mouseevent
}
}
list.init();
自定义bind
Function.prototype.mybind=function(target) {
var self=this;
var args=[].slice.call(arguments,1);
var temp =function(){};
var f=function() {
var _arg=[].slice.call(arguments,0);
return self.apply(this instanceof temp ? this :(target || window),args.concat(_arg));
}
temp.prototype=self.prototype;
f.prototype=new temp();
return f;
}
var myshow2 = show.mybind(bch,"1",12);
myshow2();
总结:
function A(){
...
}
var B={}
var x=1,y=3,z=4;
var o=A.bind(B,x,y,z);
1:函数A调用bind时,需要b,x,y,x....;
2:返回新的函数o;
3:执行o() ,具体功能还是A的,只是this的指向变成B|| window
4:执行o(),参数会拼接到x,y,z后一并在内部传递给A;
5:new o() 的构造函数是A(),而且B无任何关系