Object.prototype.Call = function(context){
if(typeof this != 'function'){
throw new TypeError('this is not a function')
}
context.fn = this;
var result= [];
var args = [];
for(var i = 1; i< arguments.length; i++){
args.push('arr[' + i + ']')
}
result = eval('context.fn(' +args+ ')');
delete context.fn;
return result;
}
Object.prototype.Apply = function(context, arr){
if(typeof this != 'function'){
throw new TypeError('this is not a function')
}
context.fn = this;
var result= [];
if(!arr){
result = context.fn()
}else{
var args = [];
for(var i = 0; i< arr.length; i++){
args.push('arr[' + i + ']')
}
result = eval('context.fn(' +args+ ')');
}
delete context.fn;
return result;
}
Object.prototype.Bind = function(){
if(typeof this != 'function'){
throw new TypeError('this is not a function')
}
var self = this;
var args = Array.prototype.slice.call(arguments,1);
var F = function(){};
F.prototype = this.prototype;
var bound = function(){
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof F ? this: context, args.concat(bindArgs))
};
bound.prototype = new F();
return bound;
}
手写call, apply和bind
最新推荐文章于 2024-06-09 22:26:02 发布