手写call方法
const person = {
getName() {
return this.name
}
}
const person1 = {
name: 'JP'
}
Function.prototype.myCall = function (context) {
if (typeof context !== 'function') {
throw new Error('只有function才可以调用call方法!')
}
context = context || window
const argu = [...arguments].slice(1)
console.log(argu)
context.fn = this
const result = context.fn(...argu)
delete context.fn
return result
}
console.log(person.getName.myCall(person1, 1, 2, 3, 4))
递归实现1-100求和
let tempArr = [1, 2, 3, 4, 5, 6]
const addNum = (a=1, b=2, c=100) => {
let num = a + b
if (b + 1 > c) {
return num
} else {
return addNum(num, b + 1)
}
}
let num = tempArr.reduce((a, b) => { return a + b }, 100)
console.log(num)