js相关函数的实现,instanceof、深拷贝、函数等

手写instanceof

// 手写instanceof
let myInstanceof = (target, origin) => {
    while(target) {
        if(target.__proto__===origin.prototype) {
            return true
        }
        target = target.__proto__
    }
    return false
}
let a = [1,2,3]
console.log(myInstanceof(a,Array)) // true
console.log(myInstanceof(a,Object)) // true 

手写深拷贝

let oldObj = {
    id: 1,
    name: 'xiaoming',
    msg: {
        age: 18
    }
}
let newObj = {}
function deepCopy(newObj, oldObj) {
    for(var k in oldObj) {
        let item = oldObj[k]
        if(item instanceof Array) {
            newObj[k] = []
            deepCopy(newObj[k], item)
        }else if(item instanceof Object) {
            newObj[k] = {}
            deepCopy(newObj[k], item)
        }else{
            newObj[k] = item
        }
    }
}
deepCopy(newObj,oldObj)
console.log(newObj)
/* {
    "id": 1,
    "name": "Male",
    "msg": {
        "age": 18
    }
} */
newObj.name = 'Male'
console.log(newObj)
/* 
{
    "id": 1,
    "name": "Male",
    "msg": {
        "age": 18
    }
}
*/
console.log(oldObj)
/* 
{
    "id": 1,
    "name": "xiaoming",
    "msg": {
        "age": 18
    }
}
*/

手写防抖

// 手写防抖
function debounce(fn, delay) {
    if(typeof fn !== 'function') {
        throw new TypeError('fn不是函数')
    }
    let timer; // 维护一个timer
    return function() {
        var _this = this // 取debounce执行作用域的this(原函数挂载到的对象)
        var args = arguments
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(function() {
            fn.apply(_this,args) // 用apply只想调用debounce的对象,相当于_this.fn(args)
        }, delay)
    }
}
input1.addEventListener('keyup',debounce(() => {
    console.log(input1.value)
}),600)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值