對bind,apply,call的用發(fā)理解還不夠深刻赌渣。
手寫一個bind方法
//context為需要被綁定上的對象,arguments是參數(shù)
Function.prototype.bind = function(context){
var self = this; //this => Function
return function(){
return self.apply(context,arguments)
}
}
再復雜一點
//context為需要被綁定上的對象,arguments是參數(shù)
Function.prototype.bind = function(){
var self = this; //this => Function
var context = [].shift.call(arguments); //arguments 的第一個為需要綁定的this上下文
var args = [].slice.call(arguments)// arguments除了第一個澡绩,成為一個數(shù)組
return function(){
return self.apply(context,[].concat.call(args,[].slice.call(arguments)))
}
}
//運行
var obj = {name: 'shaojingjing'}
var func = function(a,b,c,d){
alert(this.name); // shaojingjing
alert([a,b,c,d]) // [1,2,3,44]
}.bind(obj,1,2).(3,4)