前言
本文針對目前常見的面試題,僅提供了相應的核心原理及思路,部分邊界細節(jié)未處理。后續(xù)會持續(xù)更新,希望對你有所幫助。
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. 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__ }}5. Object.create的基本實現(xiàn)原理
// 思路:將傳入的對象作為原型function create(obj) { function F() {} F.prototype = obj return new F()6. new本質(zhì)
function myNew (fun) { return function () { // 創(chuàng)建一個新對象且將其隱式原型指向構造函數(shù)原型 let obj = { __proto__ : fun.prototype } // 執(zhí)行構造函數(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}7. 實現(xiàn)一個基本的Promise
// 未添加異步處理等其他邊界情況// ①自動執(zhí)行函數(shù),②三個狀態(tài),③thenclass 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: } }}
新聞熱點
疑難解答
圖片精選