Function.prototype.myCall = function () {
const [context, ...argu] = [...arguments]
context.fun = this
context.fun(...argu)
delete context.fun
}
const obj = {
a: '我是对象中的'
}
function fn() {
console.log(this.a, ...arguments)
}
fn.myCall(obj, [1,2], 200 ,'333', 1)
Function.prototype.myApply = function() {
const [context, argu] = [...arguments]
context.fun = this
let res = argu.length > 0 ? context.fun(...argu) : context.fun()
delete context.fun
return res
}
function fnApply() {
console.log(this.a);
console.log([...arguments]);
return [...arguments]
}
let s = fnApply.myApply(obj, [1,2,3,4,5])
console.log(s)
Function.prototype.myBind = function() {
const [context, ...args] = [...arguments];
return () => {
return this.apply(context, [...args])
}
}
const obj2 = {
value: 1,
fn: function(name) {
console.log('bind调用 '+this.value, name)
}
}
let a = obj2.fn
a()
a.bind(obj2,'周斌')()
a.myBind(obj2, '周斌')()