bind 函数 源码解析

/*
	目标函数:调用bind的函数,func.bind func就称之为是目标函数
	新函数:bind返回的函数,let newFunc = func.bind() newFunc就称之为新函数
*/

/*
	1. 返回的函数作为构造函数,新函数要继承目标函数的原型
	2. 一旦把新函数当成构造函数了,目标函数的this应该指向实例对象
*/

Function.prototype.customeBind = function (thisArg,...list){
	let self = this;  // 目标函数

	// 自己实现的bind函数,如果把返回的新函数当成了构造函数,此时会遇到问题,
          // 就是找不到目标函数原型上的方法,解决:放新函数继承目标函数的原型

	let Bound = function(...arg2){
		// 如果这个函数作为了构造函数,那么目标函数的this,应该执行的是实例对象
		// 如果这个不是作为构造函数,目标函数中的this还指向thisArg
		let thisArgSelf = this instanceof Bound ? this : thisArg;
		self.apply(thisArgSelf,[...list,...arg2])
	}

	// 原型继承
	// Object.create 用来创建以某一个对象作为原型的对象的
	Bound.prototype = Object.create(self.prototype);
	Bound.prototype.constructor = self;

	// 返回的新函数
	return Bound
}

发布于 2018-10-23 17:26