手写js中的bind方法

Function.prototype.handWrittenBind = function(){
		//const args = Array.from(arguments);
		//const thisArg = args.shift(); // 将指针和参数分开
		//const thisArg = thisArg || window; //判断传入的第一个参数
		if(typeof this !=='function') throw 'caller must be a function' // 判断是否函数在调用此方法
		let callerThis = this; // 保存调用者的this 在返回函数当调用的者的构造函数时使用
		let thisArg = arguments[0]  // 获取第一个参数
		let args =  Array.prototype.slice.call(arguments, 1); //除了指针意外的其他参数
		const  resultFn = function(){
				 let fnArgs = Array.prototype.slice.call(arguments) // 调用返回函数时传的参数
				 // this instanceof callerThis 用来判断当前的返回函数是被当做构造函数执行了
				 // 传入null/undefined的时候将执行js全局对象浏览器中是window
				 callerThis.apply(this instanceof callerThis ? this : thisArg, args.concat(fnArgs))

		}
		resultFn.prototype = Object.create(callerThis.prototype) //将返回的函数的原型指向调用者的实例上
        return resultFn
}

obj = {
	name:'张三',
	fn:function(){
			console.log(this);
	}
}
obj.fn.handWrittenBind([1,2,3])()

obj.fn.handWrittenBind(null)()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值