call、apply和bind

call

call()方法在使用一个指定的this值和若干个指定的参数值的前提下调用某个函数或方法

Function.prototype.call=function(context) {
	context=context || Window;
	context.fn=this;
	let args=[];
	for(let i=1;i<arguments.length;i++) {
		args.push("arguments["+i+"]");
	}
	let result = eval('context.fn('+args+')');
	delete context.fn;
	return result;
}

apply

Function.prototype.apply=function(context,arr){
	context=context || window;
	context.fn=this;
	let result;
	if(!arr) {
		result = context.fn();
	}else {
		let args=[];
		for(let i = 0;i<arr.length;i++) {
			args.push('arr['+i+']');
		}
		result=eval('context.fn('+args+')');
	}
	delete context.fn;
	return result
}

bind

bind()方法创建一个新函数。当这个新函数被调用时,bind()的第一参数将作为它运行时的this,之后的一序列参数将会在传递的实参前传入作为它的参数。新函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的this值被忽略,同时调用时的参数被提供给模拟函数

Function.prototype.bind=function(context) {
	if(typeof this !== 'function') {
		throw new Error("必须要是函数哦")
	}
	let self =this;
	let args = Array.prototype.slice.call(arguments,1);
	let fNOP= function (){};
	let fBound = function(){
		let boundArgs=Array.prototype.slice.call(arguments);
		return self.apply(this instanceof fNOP?this:context,args.concat(boundArgs))
	}
	fNOP.prototype=this.prototype;
	fBound.prototype=new fNOP();
	return fBound
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值