實現(xiàn) new 方法
/* * 1.創(chuàng)建一個空對象 * 2.鏈接到原型 * 3.綁定this值 * 4.返回新對象 */ // 第一種實現(xiàn) function
createNew() { let obj = {} // 1.創(chuàng)建一個空對象 let constructor =
[].shift.call(arguments) // let [constructor,...args] = [...arguments]
obj.__proto__ = constructor.prototype // 2.鏈接到原型 let result =
constructor.apply(obj, arguments) // 3.綁定this值 // let result =
constructor.apply(obj, args) return typeof result === 'object' ? result : obj
// 4.返回新對象 } function People(name,age) { this.name = name this.age = age } let
peo = createNew(People,'Bob',22) console.log(peo.name) console.log(peo.age)
實現(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(this.value) break case
'rejected': onRejected(this.value) break default: } } }
實現(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 }
實現(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 }
實現(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)) } } }
淺拷貝、深拷貝的實現(xiàn)
淺拷貝:
// 1. ...實現(xiàn) let copy1 = {...{x:1}} // 2. Object.assign實現(xiàn) let copy2 =
Object.assign({}, {x:1})
深拷貝:
// 1. JOSN.stringify()/JSON.parse() // 缺點:拷貝對象包含 正則表達式,函數(shù),或者undefined等值會失敗 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 }
實現(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))
實現(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))
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__ } }
柯里化函數(shù)的實現(xiàn)
柯里化函數(shù)最通俗易懂的一篇:js如何用一句代碼實現(xiàn)函數(shù)的柯里化(ES6) <https://www.jianshu.com/p/c87242cd2f6c>
函數(shù)柯里化的定義:接收一部分參數(shù),返回一個函數(shù)接收剩余參數(shù),接收足夠參數(shù)后,執(zhí)行原函數(shù)。
Object.create 的基本實現(xiàn)原理
// 思路:將傳入的對象作為原型 function create(obj) { function F() {} F.prototype = obj
return new F() }
實現(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
實現(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 })
詳細的實現(xiàn)見:這應(yīng)該是最詳細的響應(yīng)式系統(tǒng)講解了 <https://juejin.im/post/5d26e368e51d4577407b1dd7>
實現(xiàn)一個簡單路由
// hash路由 class Route{ constructor(){ // 路由存儲對象 this.routes = {} // 當前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]() } }
實現(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 () { // 滾動卷去的高度 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') } } } // addEventListener('scroll',
lazyLoad) or setInterval(lazyLoad, 1000)
rem 基本設(shè)置
// 提前執(zhí)行,初始化 resize 事件不會執(zhí)行 setRem() // 原始配置 function setRem () { let doc =
document.documentElement let width = doc.getBoundingClientRect().width let rem
= width / 75 doc.style.fontSize = rem + 'px' } // 監(jiān)聽窗口變化
addEventListener("resize", setRem)
手寫實現(xiàn) AJAX
// 1. 簡單流程 // 實例化 let xhr = new XMLHttpRequest() // 初始化 xhr.open(method, url,
async) // 發(fā)送請求 xhr.send(data) // 設(shè)置狀態(tài)變化回調(diào)處理請求結(jié)果 xhr.onreadystatechange = () =>
{ if (xhr.readyStatus === 4 && xhr.status === 200) {
console.log(xhr.responseText) } } // 2. 基于promise實現(xiàn) function ajax (options) {
// 請求地址 const url = options.url // 請求方法 const method =
options.method.toLocaleLowerCase() || 'get' // 默認為異步true const async =
options.async // 請求參數(shù) const data = options.data // 實例化 const xhr = new
XMLHttpRequest() // 請求超時 if (options.timeout && options.timeout > 0) {
xhr.timeout = options.timeout } // 返回一個Promise實例 return new Promise ((resolve,
reject) => { xhr.ontimeout = () => reject && reject('請求超時') // 監(jiān)聽狀態(tài)變化回調(diào)
xhr.onreadystatechange = () => { if (xhr.readyState == 4) { // 200-300
之間表示請求成功,304資源未變,取緩存 if (xhr.status >= 200 && xhr.status < 300 || xhr.status ==
304) { resolve && resolve(xhr.responseText) } else { reject && reject() } } }
// 錯誤回調(diào) xhr.onerror = err => reject && reject(err) let paramArr = [] let
encodeData // 處理請求參數(shù) if (data instanceof Object) { for (let key in data) { //
參數(shù)拼接需要通過 encodeURIComponent 進行編碼 paramArr.push(encodeURIComponent(key) + '=' +
encodeURIComponent(data[key])) } encodeData = paramArr.join('&') } // get請求拼接參數(shù)
if (method === 'get') { // 檢測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ā)送請求 if (method ===
'get') xhr.send(null) else { // post 方式需要設(shè)置請求頭
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')
xhr.send(encodeData) } }) }
2019前端面試系列——CSS面試題 <https://www.cnblogs.com/chenwenhao/p/11217590.html>
2019前端面試系列——JS面試題 <https://www.cnblogs.com/chenwenhao/p/11253403.html>
2019前端面試系列——JS高頻手寫代碼題 <https://www.cnblogs.com/chenwenhao/p/11294541.html>
2019前端面試系列——Vue面試題 <https://www.cnblogs.com/chenwenhao/p/11258895.html>
2019前端面試系列——HTTP、瀏覽器面試題 <https://www.cnblogs.com/chenwenhao/p/11267238.html>
熱門工具 換一換