手写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)