前端開發(fā)今年最??糐avaScript面試題(16題)

1. 實現(xiàn)一個call函數(shù)

// 思路:將要改變this指向的方法掛到目標this上執(zhí)行并返回
Function.prototype.mycall = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('not funciton')
  }
  context = context || window
  context.fn = this
  let arg = [...arguments].slice(1)
  let result = context.fn(...arg)
  delete context.fn
  return result
} 

2. 實現(xiàn)一個apply函數(shù)

// 思路:將要改變this指向的方法掛到目標this上執(zhí)行并返回
Function.prototype.myapply = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('not funciton')
  }
  context = context || window
  context.fn = this
  let result
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }
  delete context.fn
  return result
}

3. 實現(xiàn)一個bind函數(shù)

// 思路:類似call,但返回的是函數(shù)
Function.prototype.mybind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  let _this = this
  let arg = [...arguments].slice(1)
  return function F() {
    // 處理函數(shù)使用new的情況
    if (this instanceof F) {
      return new _this(...arg, ...arguments)
    } else {
      return _this.apply(context, arg.concat(...arguments))
    }
  }
}

4. new本質(zhì)

function myNew (fun) {
  return function () {
    // 創(chuàng)建一個新對象且將其隱式原型指向構(gòu)造函數(shù)原型
    let obj = {
      __proto__ : fun.prototype
    }
    // 執(zhí)行構(gòu)造函數(shù)
    fun.call(obj, ...arguments)
    // 返回該對象
    return obj
  }
}
function person(name, age) {
  this.name = name
  this.age = age
}
let obj = myNew(person)('chen', 18) 
// {name: "chen", age: 18}

5. Object.create的基本實現(xiàn)原理

// 思路:將傳入的對象作為原型
function create(obj) {
  function F() {}
  F.prototype = obj
  return new F()
}

6. instanceof的原理

// 思路:右邊變量的原型存在于左邊變量的原型鏈上
function instanceOf(left, right) {
  let leftValue = left.__proto__
  let rightValue = right.prototype
  while (true) {
    if (leftValue === null) {
      return false
    }
    if (leftValue === rightValue) {
      return true
    }
    leftValue = leftValue.__proto__
  }
}

7. 實現(xiàn)一個基本的Promise

// 未添加異步處理等其他邊界情況
// ①自動執(zhí)行函數(shù),②三個狀態(tài),③then
class Promise {
  constructor (fn) {
    // 三個狀態(tài)
    this.state = 'pending'
    this.value = undefined
    this.reason = undefined
    let resolve = value => {
      if (this.state === 'pending') {
        this.state = 'fulfilled'
        this.value = value
      }
    }
    let reject = value => {
      if (this.state === 'pending') {
        this.state = 'rejected'
        this.reason = value
      }
    }
    // 自動執(zhí)行函數(shù)
    try {
      fn(resolve, reject)
    } catch (e) {
      reject(e)
    }
  }
  // then
  then(onFulfilled, onRejected) {
    switch (this.state) {
      case 'fulfilled':
        onFulfilled()
        break
      case 'rejected':
        onRejected()
        break
      default:
    }
  }
}

8. 實現(xiàn)淺拷貝

// 1. ...實現(xiàn)
let copy1 = {...{x:1}}
// 2. Object.assign實現(xiàn)
let copy2 = Object.assign({}, {x:1})

9. 使用setTimeout模擬setInterval

// 可避免setInterval因執(zhí)行時間導(dǎo)致的間隔執(zhí)行時間不一致
setTimeout (function () {
  // do something
  setTimeout (arguments.callee, 500)
}, 500)

10. js實現(xiàn)一個繼承方法

// 借用構(gòu)造函數(shù)繼承實例屬性
function Child () {
  Parent.call(this)
}
// 寄生繼承原型屬性
(function () {
  let Super = function () {}
  Super.prototype = Parent.prototype
  Child.prototype = new Super()
})()

[圖片上傳失敗...(image-ece8dc-1593960210864)]

11. 實現(xiàn)一個基本的深拷貝

// 1. JOSN.stringify()/JSON.parse()
let obj = {a: 1, b: {x: 3}}
JSON.parse(JSON.stringify(obj))
// 2. 遞歸拷貝
function deepClone(obj) {
 let copy = obj instanceof Array ? [] : {}
 for (let i in obj) {
  if (obj.hasOwnProperty(i)) {
  copy[i] = typeof obj[i] === 'object'?deepClone(obj[i]):obj[i]
    }
  }
  return copy
}

12. 實現(xiàn)一個基本的Event Bus

// 組件通信,一個觸發(fā)與監(jiān)聽的過程
class EventEmitter {
  constructor () {
    // 存儲事件
    this.events = this.events || new Map()
  }
  // 監(jiān)聽事件
  addListener (type, fn) {
    if (!this.events.get(type)) {
      this.events.set(type, fn)
    }
  }
  // 觸發(fā)事件
  emit (type) {
    let handle = this.events.get(type)
    handle.apply(this, [...arguments].slice(1))
  }
}
// 測試
let emitter = new EventEmitter()
// 監(jiān)聽事件
emitter.addListener('ages', age => {
  console.log(age)
})
// 觸發(fā)事件
emitter.emit('ages', 18)  // 18

13. 實現(xiàn)一個雙向數(shù)據(jù)綁定

let obj = {}
let input = document.getElementById('input')
let span = document.getElementById('span')
// 數(shù)據(jù)劫持
Object.defineProperty(obj, 'text', {
  configurable: true,
  enumerable: true,
  get() {
    console.log('獲取數(shù)據(jù)了')
  },
  set(newVal) {
    console.log('數(shù)據(jù)更新了')
    input.value = newVal
    span.innerHTML = newVal
  }
})
// 輸入監(jiān)聽
input.addEventListener('keyup', function(e) {
  obj.text = e.target.value
})

14. 實現(xiàn)一個簡單路由

// hash路由
class Route{
  constructor(){
    // 路由存儲對象
    this.routes = {}
    // 當(dāng)前hash
    this.currentHash = ''
    // 綁定this,避免監(jiān)聽時this指向改變
    this.freshRoute = this.freshRoute.bind(this)
    // 監(jiān)聽
    window.addEventListener('load', this.freshRoute, false)
    window.addEventListener('hashchange', this.freshRoute, false)
  }
  // 存儲
  storeRoute (path, cb) {
    this.routes[path] = cb || function () {}
  }
  // 更新
  freshRoute () {
    this.currentHash = location.hash.slice(1) || '/'
    this.routes[this.currentHash]()
  }   
}

15. 實現(xiàn)一個節(jié)流函數(shù)

// 思路:在規(guī)定時間內(nèi)只觸發(fā)一次
function throttle (fn, delay) {
  // 利用閉包保存時間
  let prev = Date.now()
  return function () {
    let context = this
    let arg = arguments
    let now = Date.now()
    if (now - prev >= delay) {
      fn.apply(context, arg)
      prev = Date.now()
    }
  }
}
function fn () {
  console.log('節(jié)流')
}
addEventListener('scroll', throttle(fn, 1000)) 

16. 實現(xiàn)一個防抖函數(shù)

// 思路:在規(guī)定時間內(nèi)未觸發(fā)第二次,則執(zhí)行
function debounce (fn, delay) {
  // 利用閉包保存定時器
  let timer = null
  return function () {
    let context = this
    let arg = arguments
    // 在規(guī)定時間內(nèi)再次觸發(fā)會先清除定時器后再重設(shè)定時器
    clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(context, arg)
    }, delay)
  }
}
function fn () {
  console.log('防抖')
}
addEventListener('scroll', debounce(fn, 1000)) 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容