ES6扩展运算符实现call、apply、bind方法

465 阅读1分钟
        #call实现
        Function.prototype.myCall = function(context,...params) {
		if(!(context instanceof Object)) {
			context = {};
		}
		const fn = Symbol('call')
		context[fn] = this
		var result = context[fn](...params)
		delete context[fn]
		return result
	}
	
	#apply实现
	Function.prototype.myApply = function(context,params) {
		if(!(context instanceof Object)) {
			context = {};
		}
		const fn = Symbol('apply')
		context[fn] = this
		var result = context[fn](...params)
		delete context[fn]
		return result
	}
	
	#bind实现
	Function.prototype.myBind = function(context,...params) {
		if(!(context instanceof Object)) {
			context = {};
		}
		const that = this;
		var bindFn = function(...nextParams) {
			const isCreateByNew = this instanceof bindFn;
			const lastContext = isCreateByNew ? this : context
			return that.call(lastContext,...params,...nextParams);
		}
		bindFn.prototype = Object.create(that.prototype);
		return bindFn;
	}