bind使用
bind与call和apply的作用一致,都是改变this指向。但在使用方式上会有一些不同。
var value = 'window';
var obj = {
value:'obj'
}
function show(name,age){
console.log(this.value);
console.log(name,age);
}
show('hkp',18); //widnow hkp 18
//传参数的方式不同,会有相同的结果
var newshow = show.bind(obj);
newshow('hkp',18); //obj hkp 18
var newshow = show.bind(obj,'hkp');
newshow(18); //obj hkp 18
var newshow = show.bind(obj,'hkp',18)
newshow(); //obj hkp 18
var newshow = show.bind(null,'hkp',18); //第一个参数为null, this指向window
newshow(); //window hkp 18
var newshow = show.bind(obj,'hkp');
new newshow(18); //undefined hkp 18
//newshow是一个函数,new操作构造出一个对象 new操作之后就会改变this指向 指向newshow构造出的对象
bind模拟实现(对应以上代码)
1.函数show在调用bind方法时,需要传递参数obj,x,y,z…等参数
2.返回新的函数newShow
3.函数newShow在执行的时候, 具体的功能实际上还是使用show, 只不过this指向变成了obj或者window
4.函数newShow在执行的时候 ,传递的参数会拼接到x,y,z后面一并在内部传递个show执行
5.new newShow() 构造函数依旧是show, 而且参数obj不会起到任何作用 new()改变this指向优先级高于bind call apply
Function.prototype.newBind = function(target){
target = target || window;
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,args.concat(arg));
}
temp.prototype = this.prototype;
F.prototype = new temp();
return F;
}
var newShow = show.newBind(obj,'hkp',18);
newShow(); //obj hkp 18
console.log(new newShow().constructor)//show函数体