blog
blog copied to clipboard
模拟实现一个call、apply、bind方法
模拟实现bind方法
if(!Function.prototype.bind){
Function.prototype.bind = function(oThis){
if(typeof this !== 'function'){
throw new TypeError();
}
var aArgs = [].slice.call(arguments,1),
self = this,
fNOP = function(){},
fBound = function() {
return self.apply(this instanceof fNOP
? this
: oThis,
aArgs.concat([].slice.call(arguments)));
};
if(this.prototype){
fNOP.prototype = this.prototype;
}
fBound = new fNOP();
return fBound;
};
}
模拟实现一个call与apply方法
思路
- 将函数设为对象属性
- 执行该函数
- 删除该函数
call
Function.prototype.call = function(context){
var context = cotext || window;
context.fn = this;
var args = [];
for(var i = 1; i < arguments.length; i++){
args.push('arguments['+i+']');
}
var result = eval('context.fn('+args+')');
delete context.fn;
return result;
}
apply
Function.prototype.apply = function(context, arr){
var context = context || window;
contex.fn = this;
var reslut = [];
if(!arr){
result = context.fn(arr);
}else{
var args = [];
for(var i = 0; i < arr.length; i++){
args.push('arguments['+i+']');
}
result = eval('context.fn('+arr')');
}
delete context.fn;
return result;
}
三者区别
- call和apply的区别是传入的参数不同,
- apply 方法传入两个参数:一个是作为函数上下文的对象,另外一个是作为函数参数所组成的数组
- call 方法第一个参数也是作为函数上下文的对象,但是后面传入的是一个参数列表,而不是单个数组。 call和apply与 bind 最大的区别是 call apply调用即执行了所对应的方法,bind的返回值是改变指向后的这个函数(未执行)