20道原理題解析

前言

本文引自于javascript公眾號(hào),致力于讓更多的人了解大廠常見面試題绩脆,其中加入了解析思路萤厅,提供給大家。

\color{#4A33EE}{1.實(shí)現(xiàn)call函數(shù)}
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
}

解析:

  1. 不了解call用法的請(qǐng)看:call 方法和 apply 方法的作用及意義靴迫;
  2. 如果僅僅想改變this的指向:
Function.prototype.mycall = function (context) {
  context = context || window
  context.fn = this  // 此時(shí)的this代表的是foo函數(shù)
  context.fn()  // 僅僅是調(diào)用一下foo函數(shù)
  console.log(context, this); // 此時(shí)我們打印一下惕味,會(huì)發(fā)現(xiàn)fn是context下的一個(gè)方法,很自然的我們知道this指向了context對(duì)象玉锌,也就是傳遞過來的obj名挥。(不明白的,得惡補(bǔ)一下this指向主守。)
}

// 舉例:
const obj = {
  name: '小米'
};

function foo() {
  console.log(this.name);
}

foo.myCall(obj);

此時(shí)我們打印一下console.log(context, this)禀倔,會(huì)發(fā)現(xiàn)fncontext下的一個(gè)方法,很自然的我們知道this指向了context對(duì)象丸逸,也就是傳遞過來的obj蹋艺。(不明白的,得惡補(bǔ)一下this指向黄刚。)

image.png

3.其他的方法就是為了傳參存在捎谨,就是傳單個(gè)怎么獲取的問題,這個(gè)稍微研究一下就理解了。


\color{#4A33EE}{2.實(shí)現(xiàn)apply函數(shù)}
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
}

\color{#4A33EE}{3.實(shí)現(xiàn)bind函數(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))
    }
  }
}

\color{#4A33EE}{4. instanceof的原理}
// 右邊變量的原型存在于左邊變量的原型鏈上
function instanceOf(left, right) {
  let leftValue = left.__proto__
  let rightValue = right.prototype
  while (true) {
    if (leftValue === null) {
      return false
    }
    if (leftValue === right) {
      return true
    }
    leftValue = rightValue.__proto__
  }
}

簡(jiǎn)單來說:如A instanceof B涛救,就是A是不是B的實(shí)例畏邢;實(shí)現(xiàn)原理就是:變量查找A的原型鏈,找到與B. prototype上相等的即A是B的實(shí)例检吆,如果找不到則不是舒萎。 深入原理:自行了解原型鏈。


\color{#4A33EE}{5. Object.create的基本實(shí)現(xiàn)原理}
function create(obj) {
  function F() {}
  F.prototype = obj
  return new F()
}

用空函數(shù)F創(chuàng)建實(shí)例蹭沛,避免了多次調(diào)用父類的情況臂寝。


\color{#4A33EE}{6. new本質(zhì)}
function myNew (fun) {
  return function () {
    // 創(chuàng)建一個(gè)新對(duì)象且將其隱式原型指向構(gòu)造函數(shù)原型
    let obj = {
      __proto__ : fun.prototype
    }
    // 執(zhí)行構(gòu)造函數(shù)
    fun.call(obj, ...arguments)
    // 返回該對(duì)象
    return obj
  }
}

\color{#4A33EE}{7. 實(shí)現(xiàn)一個(gè)基本的Promise}
// ①自動(dòng)執(zhí)行函數(shù),②三個(gè)狀態(tài)摊灭,③then
class Promise {
  constructor (fn) {
    // 三個(gè)狀態(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
      }
    }
    // 自動(dòng)執(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:
    }
  }
}

\color{#4A33EE}{8. 實(shí)現(xiàn)淺拷貝}
// 1. ...實(shí)現(xiàn)
let copy1 = {...{x:1}}

// 2. Object.assign實(shí)現(xiàn)

let copy2 = Object.assign({}, {x:1})

\color{#4A33EE}{9. 實(shí)現(xiàn)一個(gè)基本的深拷貝}
// 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
}

\color{#4A33EE}{10. 使用setTimeout模擬setInterval}
// 可避免setInterval因執(zhí)行時(shí)間導(dǎo)致的間隔執(zhí)行時(shí)間不一致
setTimeout (function () {
  // do something
  setTimeout (arguments.callee, 500)
}, 500)

\color{#4A33EE}{11. js實(shí)現(xiàn)一個(gè)繼承方法// 借用構(gòu)造函數(shù)繼承實(shí)例屬性}
function Child () {
  Parent.call(this)
}
// 寄生繼承原型屬性
(function () {
  let Super = function () {}
  Super.prototype = Parent.prototype
  Child.prototype = new Super()
})()

\color{#4A33EE}{12. 實(shí)現(xiàn)一個(gè)基本的Event Bus}

// 組件通信咆贬,一個(gè)觸發(fā)與監(jiān)聽的過程
class EventEmitter {
  constructor () {
    // 存儲(chǔ)事件
    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))
  }
}

// 測(cè)試
let emitter = new EventEmitter()
// 監(jiān)聽事件
emitter.addListener('ages', age => {
  console.log(age)
})
// 觸發(fā)事件
emitter.emit('ages', 18)  // 18

\color{#4A33EE}{13. 實(shí)現(xiàn)一個(gè)雙向數(shù)據(jù)綁定}
let obj = {}
let input = document.getElementById('input')
let span = document.getElementById('span')
Object.defineProperty(obj, 'text', {
  configurable: true,
  enumerable: true,
  get() {
    console.log('獲取數(shù)據(jù)了')
    return obj.text
  },
  set(newVal) {
    console.log('數(shù)據(jù)更新了')
    input.value = newVal
    span.innerHTML = newVal
  }
})
input.addEventListener('keyup', function(e) {
  obj.text = e.target.value
})

\color{#4A33EE}{14. 實(shí)現(xiàn)一個(gè)簡(jiǎn)單路由}

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

\color{#4A33EE}{15. 實(shí)現(xiàn)懶加載}
<ul>
  <li><img src="./imgs/default.png" data="./imgs/1.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/2.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/3.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/4.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/5.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/6.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/7.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/8.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/9.png" alt=""></li>
  <li><img src="./imgs/default.png" data="./imgs/10.png" alt=""></li>
</ul>
let imgs =  document.querySelectorAll('img')
// 可視區(qū)高度
let clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
function lazyLoad () {
  // 滾動(dòng)卷去的高度
  let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  for (let i = 0; i < imgs.length; i ++) {
    // 得到圖片頂部距離可視區(qū)頂部的距離
    let x = clientHeight + scrollTop - imgs[i].offsetTop
    // 圖片在可視區(qū)內(nèi)
    if (x > 0 && x < clientHeight+imgs[i].height) {
      imgs[i].src = imgs[i].getAttribute('data')
    }
  }
}
setInterval(lazyLoad, 1000)

\color{#4A33EE}{16. rem實(shí)現(xiàn)原理}
function setRem () {
  let doc = document.documentElement
  let width = doc.getBoundingClientRect().width
  // 假設(shè)設(shè)計(jì)稿為寬750帚呼,則rem為10px
  let rem = width / 75
  doc.style.fontSize = rem + 'px'
}

\color{#4A33EE}{17. 手寫實(shí)現(xiàn)AJAX}

// 1. 簡(jiǎn)單實(shí)現(xiàn)

// 實(shí)例化
let xhr = new XMLHttpRequest()
// 初始化
xhr.open(method, url, async)
// 發(fā)送請(qǐng)求
xhr.send(data)
// 設(shè)置狀態(tài)變化回調(diào)處理請(qǐng)求結(jié)果
xhr.onreadystatechange = () => {
  if (xhr.readyStatus === 4 && xhr.status === 200) {
    console.log(xhr.responseText)
  }
}

// 2. 基于promise實(shí)現(xiàn)

function ajax (options) {
  // 請(qǐng)求地址
  const url = options.url
  // 請(qǐng)求方法
  const method = options.method.toLocaleLowerCase() || 'get'
  // 默認(rèn)為異步true
  const async = options.async
  // 請(qǐng)求參數(shù)
  const data = options.data
  // 實(shí)例化
  const xhr = new XMLHttpRequest()
  // 請(qǐng)求超時(shí)
  if (options.timeout && options.timeout > 0) {
    xhr.timeout = options.timeout
  }
  // 返回一個(gè)Promise實(shí)例
  return new Promise ((resolve, reject) => {
    xhr.ontimeout = () => reject && reject('請(qǐng)求超時(shí)')
    // 監(jiān)聽狀態(tài)變化回調(diào)
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        // 200-300 之間表示請(qǐng)求成功掏缎,304資源未變,取緩存
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
          resolve && resolve(xhr.responseText)
        } else {
          reject && reject()
        }
      }
    }
    // 錯(cuò)誤回調(diào)
    xhr.onerror = err => reject && reject(err)
    let paramArr = []
    let encodeData
    // 處理請(qǐng)求參數(shù)
    if (data instanceof Object) {
      for (let key in data) {
        // 參數(shù)拼接需要通過 encodeURIComponent 進(jìn)行編碼
        paramArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
      }
      encodeData = paramArr.join('&')
    }
    // get請(qǐng)求拼接參數(shù)
    if (method === 'get') {
      // 檢測(cè)url中是否已存在 ? 及其位置
      const index = url.indexOf('?')
      if (index === -1) url += '?'
      else if (index !== url.length -1) url += '&'
      // 拼接url
      url += encodeData
    }
    // 初始化
    xhr.open(method, url, async)
    // 發(fā)送請(qǐng)求
    if (method === 'get') xhr.send(null)
    else {
      // post 方式需要設(shè)置請(qǐng)求頭
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')
      xhr.send(encodeData)
    }
  })
}

\color{#4A33EE}{18. 實(shí)現(xiàn)拖拽}
window.onload = function () {
  // drag處于絕對(duì)定位狀態(tài)
  let drag = document.getElementById('box')
  drag.onmousedown = function(e) {
    var e = e || window.event
    // 鼠標(biāo)與拖拽元素邊界的距離 = 鼠標(biāo)與可視區(qū)邊界的距離 - 拖拽元素與邊界的距離
    let diffX = e.clientX - drag.offsetLeft
    let diffY = e.clientY - drag.offsetTop
    drag.onmousemove = function (e) {
      // 拖拽元素移動(dòng)的距離 = 鼠標(biāo)與可視區(qū)邊界的距離 - 鼠標(biāo)與拖拽元素邊界的距離
      let left = e.clientX - diffX
      let top = e.clientY - diffY
      // 避免拖拽出可視區(qū)
      if (left < 0) {
        left = 0
      } else if (left > window.innerWidth - drag.offsetWidth) {
        left = window.innerWidth - drag.offsetWidth
      }
      if (top < 0) {
        top = 0
      } else if (top > window.innerHeight - drag.offsetHeight) {
        top = window.innerHeight - drag.offsetHeight
      }
      drag.style.left = left + 'px'
      drag.style.top = top + 'px'
    }
    drag.onmouseup = function (e) {
      this.onmousemove = null
      this.onmouseup = null
    }
  }
}

\color{#4A33EE}{19. 實(shí)現(xiàn)一個(gè)節(jié)流函數(shù)}
function throttle (fn, delay) {
  // 利用閉包保存時(shí)間
  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))

\color{#4A33EE}{20. 實(shí)現(xiàn)一個(gè)防抖函數(shù)}
function debounce (fn, delay) {
  // 利用閉包保存定時(shí)器
  let timer = null
  return function () {
    let context = this
    let arg = arguments
    // 在規(guī)定時(shí)間內(nèi)再次觸發(fā)會(huì)先清除定時(shí)器后再重設(shè)定時(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)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末煤杀,一起剝皮案震驚了整個(gè)濱河市眷蜈,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌沈自,老刑警劉巖酌儒,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異枯途,居然都是意外死亡今豆,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門柔袁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人异逐,你說我怎么就攤上這事捶索。” “怎么了灰瞻?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵腥例,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我酝润,道長(zhǎng)燎竖,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任要销,我火速辦了婚禮构回,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己纤掸,他們只是感情好脐供,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著借跪,像睡著了一般政己。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上掏愁,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天歇由,我揣著相機(jī)與錄音,去河邊找鬼果港。 笑死沦泌,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的京腥。 我是一名探鬼主播赦肃,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼公浪!你這毒婦竟也來了他宛?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤欠气,失蹤者是張志新(化名)和其女友劉穎厅各,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體预柒,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡队塘,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了宜鸯。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片憔古。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖淋袖,靈堂內(nèi)的尸體忽然破棺而出鸿市,到底是詐尸還是另有隱情,我是刑警寧澤即碗,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布焰情,位于F島的核電站,受9級(jí)特大地震影響剥懒,放射性物質(zhì)發(fā)生泄漏内舟。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一初橘、第九天 我趴在偏房一處隱蔽的房頂上張望验游。 院中可真熱鬧充岛,春花似錦、人聲如沸批狱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽赔硫。三九已至炒俱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間爪膊,已是汗流浹背权悟。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留推盛,地道東北人峦阁。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像耘成,于是被迫代替她去往敵國(guó)和親榔昔。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容