js手写Apply
let name = "windowName"
let man = {
name: 'manName'
}
let person = {
getName: function () {
return this.name
}
}
Function.prototype.myApply = function (context) {
if (typeof this !== 'function') {
throw new Error('this is not a function')
}
context = context || window
context.fn = this
let result
// 判断是否有除了第一个参数之外的参数
if (arguments[1]) {
result = context.fn(...arguments)
} else {
result = context.fn()
}
delete context.fn
return result
}
console.log(person.getName.myApply(man, [1, 2, 3]))//manName