公共函数
function isFunction (fn) {
return typeof fn === 'function'
}
let obj = {}
function fn (name, age) {
this.name = name
this.age = age
}
call
Function.prototype.myCall = function (obj, ...arg) {
if (!isFunction(this)) return;
const fn = Symbol('fn');
obj = Object(obj);
obj[fn] = this;
const result = obj[fn](...arg);
delete obj[fn];
return result
}
Function.prototype.call = function(target, ...arg) {
if (!this instanceof Function) {
throw new Error('不是个函数')
}
let fn = Symbol("fn");
target = new Object(target)
target[fn] = this;
const result = target[fn](...arg);
Reflect.deleteProperty(target, fn)
return result;
}
apply
Function.prototype.myApply = function(obj, argArray) {
if (!isFunction(this)) return;
if (Array.isArray(argArray)) {
return this.myCall(obj, ...argArray);
} else {
return;
}
}
Function.prototype.apply = function(target, argArray) {
if (!this instanceof Function) {
throw new Error('不是个函数')
}
if (Array.isArray(argArray)) {
return this.call(target, ...argArray)
} else {
throw new Error('apply的第二个参数必须是个数组')
}
}
bind
Function.prototype.myBind = function (obj, ...arg) {
if (!isFunction(this)) return;
let bound,
self = this;
bound = function (...argB) {
let _self = this instanceof self ? this : obj;
return self.apply(_self, [...arg, ...argB]);
}
bound.prototype = Object.create(self.prototype);
bound.constructor = self;
return bound;
}
Function.prototype.bind = function(target, ...arg1) {
if (!this instanceof Function) {
throw new Error('不是个函数')
}
let self = this;
const bound = function(...arg2) {
const _self = this instanceof self ? this : target;
return self.apply(_self, [...arg1, ...arg2]);
}
bound.prototype = Object.create(self.prototype);
bound.constructor = self;
return
}
测试
fn.myCall(obj, 'swg', 26);
console.log(obj)