1.手撕代码
debounce: 防抖
const button = document.querySelector('input')
button.addEventListener('click', debounce(payMoney, 1000))
function payMoney () {
console.log('已剁手')
}
function debounce(func, delay) {
let timer;
return function () {
let context = this
let args = arguments
clearTimeout(timer)
timer = setTimeout(function () {
func.apply(context, args)
}, delay)
}
}
throttle: 节流
function throttle(func, delay) {
let pre = 0
return function () {
let context = this
let now = new Date()
let args = arguments
if(now - pre > delay) {
func.apply(context, atgs)
pre = now
}
}
}
promise
- constructor里面设置三种状态,exector去执行
- then方法
class myPromise {
constructor(executor) {
this.state = 'pending'
this.value = undefined
this.reason = undefined
this.onResolvedCallback = []
this.onRejectedCallback = []
let resolve = value => {
if (this.state === 'pending') {
this.value = value
this.state = 'fulfilled'
this.onResolvedCallback.forEach(fn => fn())
}
}
let reject = reason => {
if (this.state === 'pending') {
this.reason = reason
this.state = 'rejected'
this.onRejectedCallback.forEach(fn => fn())
}
}
try {
executor(resolve, reject)
} catch (reason) {
reject(reason)
}
}
then(onFulFilled, onRejected) {
if (this.state === 'fulfilled') {
onFullFilled(this.value)
}
if (this.state === 'rejected') {
onRejected(this.value)
}
if (this.state === 'pending') {
this.onResolvedCallback.push(() =>{
onFullFilled(this.value)
})
this.onRejectedCallback.push(() =>{
onRejected(this.reason)
})
}
}
}
const p = new myPromise((resolve, reject) => {
setTimeout(() =>{
console.log(10)
resolve(10)
})
})
p.then(
function (value) {
console.log(value + 1)
},
function (reason) {
console.log(reason)
}
)
2. js相关
2.1 判断对象类型?
Object.prototype.toString.call([]);
Object.prototype.toString.call({});
{} instanceof Object
3. VUE相关
3.1 vue如何通信
- 父子组件props和this.$emit
- 自定义事件:
this.xxxRef.on(eventName,fn);this.xxxRef.off(eventName, fn)
//在外侧调用时:this.$board.on('xxx-cahnge, ()=>{})