js中call、apply、bind实现

bind实现函数柯里化来实现的

// 常见的形式this.onPress.bind(this,params1,params2);
context 是个函数
Function.prototype.bind = function (context) {
	// 1设置变量
	let _this = this || window;
	// 1拿到参数
	let _args = Array.prototype.slice.call(arguments,1);
	return function() {
		_this.apply(context,_args);
	}
}

call实现

/*
* this: 表示谁去调用call
* context:表示传人的对象,你想绑定的对象
* arguments: 表示传人的参数
* 本质: 一个新的对象并且这个对象拥有传入的所有参数,并且this指向为传人的对象
*/
// add.call(add,params1,params2);
Function.prototype.mycall = function(context) {
	// 判断this是否是function
	if(typeof this !== 'function') {
		throw new TypeError('not funciton');
	}
	//  得到params1 params2
	let _args = [...arguments].slice(1);
	context = context || window;
	context.fn = this;
	let result = context.fn(..._args);
	delete context.fn;
	return result;
}

apply实现

// add.myApply(add,[params1,params2]);
Function.prototype.myApply = function(object,arr){
    object.__proto__._fn = this;
    var result = object._fn(...arr);
    delete object.__proto__._fn;
    return result;
}
add(1)(1,2);函数柯里化实现
function add() {
	// 1.拿到第一次的参数存储到数组中
	let _args = [...arguments];
	// let _args = Array.prototype.slice.call(arguments);
	// 2.定义返回的变量,在这里进行下次的参数保存
	let _adder = function() {
		_args = [..._args,...arguments];
		// _args.push(...arguments);
		return _adder;
	}
	// 3.隐私转换reduce把结果累加器返回
	_adder.toString = function() {
		return _args.reduce((a,b) => a+b);
	}
	// 返回一个函数对象用于下次调用。
	return _adder;
}	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值