编辑代码

//JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
console.log("Hello JSRUN!   \n\n         - from NodeJS .");

// 1.apply实现bind

function bind (context, ...args) {
    return function() {
        console.log('context', context)
        console.log('args', args)
        return Function.prototype.apply(context, args)
    }
}
var a = 2

function b () {
    // console.log('this', this)
    console.log('a', this.a)
}

const test = {
    a: 1
}

b()
b.bind(test)


// 2.deepClone

// 克隆数组有问题
function deepClone (origin) {
    if (!origin) return;
    let target = {}
    for (let key in origin) {
        if (typeof origin[key] === 'object') {
            if (origin[key] instanceof Array) {
                target[key] = []
                target[key].push(deepClone(origin[key]))
            } else {
                target[key] = {}
                target[key] = deepClone(origin[key])
            }
        } else {
            target[key] = origin[key]
        }
    }
    return target
}

// 改进
function deepClone (origin) {
    if (!origin) return
    if (typeof origin === 'object') {
        let target = Array.isArray(target) ? [] : {}
        for (const key in origin) {
            target[key] = deepClone(origin[key])
        }
        return target
    } else {
        return target
    }
}

// 3.节流(throttle) 时间戳

const throttle = (fn, delay) => {
    let lastTime;
    return (...args) => {
        let now = Date.now()
        if (lastTime + delay < now) {
            lastTime = now
            return fn(...args)
        }
        return
    }
}

throttle(2, 3, 4, 5)