1.手写call
call
let parent = {
add: function(a, b) {
return a+b
}
}
let obj = {}
Object.prototype.Mycall = function (obj) {
if (typeof this !== 'function') {
console.log("type error")
return
}
let context = obj || window
let key = Symbol()
context[key] = this
let arg = [...arguments].slice(1)
let result = context[key](...arg)
delete context[key]
return result
}
console.log(parent.add.Mycall(obj, 1, 2))
2.手写appy
let parent = {
add: function(a, b) {
return a+b
}
}
let obj = {}
Object.prototype.MyApply = function (obj) {
if (typeof this !== 'function') {
console.log("type error")
return
}
let context = obj || window
let key = Symbol()
context[key] = this
let result
if (arguments[1]) {
result = context[key](...arguments[1])
} else {
result = context[key]()
}
delete context[key]
return result
}
console.log(parent.add.MyApply(obj, [1, 2]))
3.手写bind