前端面经

190 阅读1分钟

1.手撕代码

debounce: 防抖

  • 创建变量,高阶函数形成闭包
  • 清除延时
  • 设置延时
const button = document.querySelector('input')
// 延时1s
button.addEventListener('click', debounce(payMoney, 1000))
function  payMoney () {
    console.log('已剁手')
        // this指向window
}
function debounce(func, delay) {
    // 给延时定义timeID
    let timer;
    // 函数里面返回函数,高阶函数
    // 作用域链(闭包)
    // js允许在没有参数的情况下传入参数,需要把参数给func
    return function () {
       let context = this
        let args = arguments
        clearTimeout(timer)
        timer = setTimeout(function () {
            // call 来绑定这个this给payMoney
            // func.call(context) 加了参数使用apply,而且区别为参数不用
           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) => {
    // resolve(10)
    setTimeout(() =>{
        console.log(10)
       resolve(10)
    })
})
    p.then(
    function (value) {
        console.log(value + 1)
    },
    function (reason) {
        console.log(reason)
    }
)

2. js相关

2.1 判断对象类型?

// 获得[object Type]的字符串
Object.prototype.toString.call([]);  // [object Array]
Object.prototype.toString.call({});  // [object Object]

// instanceof 可以正确的判断对象类型
{} instanceof Object  // true

3. VUE相关

3.1 vue如何通信

  • 父子组件props和this.$emit
  • 自定义事件: this.xxxRef.on(eventName,fn);this.xxxRef.on(eventName, fn); this.xxxRef.off(eventName, fn) //在外侧调用时:this.$board.on('xxx-cahnge, ()=>{})