Function.prototype.bind = function(thisArg) {
if (typeof this !== 'function') return;
const _self = this;
const args = Array.prototype.slice.call(arguments, 1)
const f = function() {
return Reflect.apply(_self, this instanceof _self ? this : (thisArg || window), args.concat(Array.prototype.slice.call(arguments))); // 注意参数的处理
}
f.prototype = this.prototype
return f
}
Function.prototype.bind1 = function(thisArg, ...args) {
if (typeof this !== 'function') return;
const _self = this;
const f = function() {
return Reflect.apply(_self, this instanceof _self ? this : (thisArg || window), args.concat(Array.from(arguments))); // 注意参数的处理
}
f.prototype = this.prototype
return f
}
function foo(name) {
this.name = name;
}
const obj = {}
const bar = foo.bind1(obj)
bar('mary') // obj { name: 'mary' }
const tom = new foo('tom') // foo { name: 'tom' }
Function.prototype.call = function(thisArg, ...args) {
thisArg.tempFn = this
const result = thisArg.tempFn(...args)
Reflect.deleteProperty('tempFn')
return result
}
Function.prototype.apply = function(thisArg, ...args) {
thisArg.tempFn = this
const result = thisArg.tempFn(args)
Reflect.deleteProperty('tempFn')
return result
}
网友评论