实现call
Function.prototype._call = function (obj, ...args) {
if (!(typeof this == "function" && typeof obj == "object")) {
return;
}
obj.fn = this;
if (args && args.length > 0) {
return obj.fn(...args);
} else {
return obj.fn();
}
}
实现apply
Function.prototype._apply = function (obj, args) {
if (!(typeof this == "function" && typeof obj == "object")) {
return;
}
obj.fn = this;
if (args && args.length > 0) {
return obj.fn(...args);
} else {
return obj.fn();
}
}
实现bind
Function.prototype._bind = function () {
if (!(typeof this == "function" && arguments.length > 0)) {
return;
}
var self = this; //保存原函数
var context = [].shift.call(arguments); //保存需要绑定的this上下文
var args = [].slice.call(arguments); //将剩余参数转化为数组
return function () {
self.apply(context, [].concat.call(args, [].slice.call(arguments)));
}
}