bind函数模拟实现

bind函数模拟实现

console.log(Function.prototype.bind)  // function
console.log(Function.prototype.bind())  // function
console.log(Function.prototype.bind.name)  // bind
console.log(Function.prototype.bind().name)  // bound
以上可以看出bind是函数Function原型链上的属性,bind是一个函数,bind执行完之后返还得还是一个函数,改函数得名称为bound
bind函数使用动态的绑定this,相比很多写react的时候用过bind动态的绑定this,看下面的代码
var foo = {
	name: 'wucr'
}
function getInfo(sex,age){
	console.log(this.name,sex,age)
	return false;
}
var bound = getInfo.bind(foo,'女');
var result = bound('12')   // wucr 女 12
console.log(result) // false
根据以上运行得出结论
  1. bind函数里面的this指向它传递参数的第一个参数对象
  2. 在调用bind的时候参数也被接收了,也就是说bound函数里面的参数是别合并了
  3. bind后的返回值函数,执行后返回值是原函数(original)的返回值。
第一版bind实现
Function.prototype.bind1 = function(thisArg){
	var args= [].slice.call(arguments,1) // 去除第一个参数的其他参数
	var self = this;
	console.log(this)
	var bound = function(){
		var boundArg = [].slice.call(arguments,0)
		self.apply(thisArg,args.concat(boundArg))
	}
	return bound 
}

以上就是初版bind的实现,但是有一个问题就是,bind返回的函数,有可能会被new 当作一个构造函来用,所以还是需要补充一下的方法

Function.prototype.bindFn = function(thisArg){
	var args= [].slice.call(arguments,1) // 去除第一个参数的其他参数
	var self = this;
	var bound = function(){
		var boundArg = [].slice.call(arguments,0)
		var finalArg = args.concat(boundArg)
		if(this instanceof bound ){
			bound.prototype = Object.create(self.prototype);
			var result = self.apply(this,finalArg )
			if(typeof result  === 'object' || typeof result === 'function'){
			    return result  
			}else{
				return this;
			}
		}else{
			return self.apply(thisArg,finalArg)
		}
		
	}
	return bound 
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值