能实现一个new吗
要实现new操作符,就要知道new + 构造函数都做了什么?
- 创建一个空的对象
- 将空对象的__proto__属性指向构造函数的原型
- 将this指向这个对象
- 返回这个对象
function newFun(context) {
// 创建一个空的对象
var obj = {
}
// 将空对象的__proto__属性指向构造函数的原型
obj.__proto__ = context.prototype;
// 将this指向这个对象 将传入的实参分割出来指向obj上
context.apply(obj, [].slice.call(arguments, 1))
return obj;
}
function Person(name, age) {
this.name = name;
this.age = age
}
var t = newFun(Person, '小张', 20)
数组扁平化
通过不断递归+跳出条件
function newFlat(arr) {
let res = new Array()
arr.forEach((item) => {
if (Array.isArray(item)) {
res.push(...newFlat(item))
} else {
res.push(item)
}
})
return res
}
用过instanceof吗,什么用法,如何手写?
首先要知道是怎么用的?
instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上
实例 instanceof 构造函数存在返回true不存在false
例子
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city
}
const a = new Person('小王', 20, '上海')
console.log(a instanceof Person) // true
知道了instanceof的用法之后手动实现instanceof
function instanceOf(instance, constructor) {
let prototype = constructor.prototype
while(true) {
if (instance == null) {
return false
}
if (instance.__proto__ == constructor.prototype) {
return true
}
instance = instance.__proto__
}
}
// 测试
function Person(name, age) {
this.name = name;
this.age = age;
}
let a = new Person('小明', 20);
console.log(instance_of(a, Person)) // true
防抖节流
防抖: 事件被调用后,在执行之前无论被调用多少次都会从头开始计时
节流: 不管事件被调用多少次,总是按照规定时间间隔执行
防抖
function debounce(func, delay = 1000, immediate = false)