call, apply, bind的模拟实现
call的模拟实现
Function.prototype._call = function() {
var context = context || window;
context.fn = this;
var args = [];
for (var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments['+ i +']')
}
var res = eval('context.fn('+ args +')');
delete context.fn;
return res;
}
Function.prototype._call = function() {
let context = arguments[0];
context.fn = this;
let args = [];
for (let i = 0, len = arguments.length; i < len; i++) {
args.push(arguments[i]);
}
let res = context.fn({...args});
delete context.fn;
return res;
}
apply的模拟实现
Function.prototype._apply = function(context, arr) {
var context = Object(context) || window;
context.fn = this;
let res;
if (!arr) {
res = context.fn();
}
else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push('arr['+i+']');
}
res = eval('context.fn('+args+')');
}
delete context.fn;
return res;
}
Function.prototype._apply = function(context) {
context = context || window;
context.fn = this;
let res;
if (arguments[1]) {
res = context.fn(...arguments[1]);
}
else {
res = context.fn();
}
delete context.fn;
return res;
}
bind的模拟实现
Function.prototype._bind = function(context) {
if (typeof this !== 'function') {
throw new Error('error callback');
}
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fnOP = function() {};
var fnBind = function() {
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof fnOP
? this
: context
, args.concat(bindArgs));
}
fnOP.prototype = this.prototype;
fnBind.prototype = new fnOP();
return fnBind;
}
Function.prototype._bind = function(context, ...args) {
let self = this;
return function() {
self.apply(context, args.concat(Array.prototype.slice.call(arguments)));
}
}
Function.prototype._bind = function(context) {
context = context || window;
let args = Array.prototype.slice.call(arguments, 1);
let self = this;
let temp = function(){};
let F = function() {
self.apply(this instanceof temp
? this
: context
, args.concat(Array.prototype.slice.call(arguments)))
}
temp.prototype = this.prototype;
F.prototype = new temp();
return F;
}