手写实现javaScript方法

100 阅读1分钟
手写call方法
   const person = {
        getName() {
            return this.name
        }
    }
    const person1 = {
        name: 'JP'
    }
    Function.prototype.myCall = function (context) {
        // 判断是否是function类型
        if (typeof context !== 'function') {
            throw new Error('只有function才可以调用call方法!')
        }
        // 处理默认上下文对象
        context = context || window
        // 处理参数,截取除了第一个参数以外的所有参数
        const argu = [...arguments].slice(1)
        console.log(argu)
        // 处理调用方法的this指向
        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)