apply
Function.prototype.myApply = function(newThis, args) {
Object.prototype.tmpFunc = this;
newThis.tmpFunc(...args);
delete Object.prototype.tmpFunc;
}
function fn1(a, b, c) {
console.log('this', this)
console.log(a, b, c)
}
fn1.myApply({ x: 100 }, [10, 20, 30])
bind
Function.prototype.bind1 = function () {
const args = Array.prototype.slice.call(arguments)
const t = args.shift()
const self = this
return function () {
return self.apply(t, args)
}
}
function fn1(a, b, c) {
console.log('this', this)
console.log(a, b, c)
return 'this is fn1'
}
const fn2 = fn1.bind1({x: 100}, 10, 20, 30)
const res = fn2()
console.log(res)
call
Function.prototype.myCall = function () {
const args = Array.prototype.slice.call(arguments);
const newThis = args.shift();
Object.prototype.tmpFunc = this;
newThis.tmpFunc(...args);
delete Object.prototype.tmpFunc;
}
function fn1(a, b, c) {
console.log('this', this)
console.log(a, b, c)
}
fn1.myCall({ x: 100 }, 10, 20, 30)