疫情無情人有情,在去年經歷互聯網一系列的風波以後,我相信你們有不少的小夥伴想在今年金三銀四的面試季中爲本身的將來找一個好一點的公司。那麼今天咱們來說解一下身爲 P5 工程師須要知道的一些原理及其如何親自手寫出它的實現過程,有可能咱們平常開發業務的時候用不上這些本身寫的方法,可是咱們咱們對原理一無所知,那麼在面試的時候一旦被深挖那麼可能離本身心念的公司就會又遠一步。前端
Function.prototype.myCall = function(context,...args){ context = (context ?? window) || new Object(context); const key = Symbol(); context[key] = this; const result = context[key](...args); delete context[key]; return result; }
Function.prototype.myApply = function(context) { context = (context ?? window) || new Object(context) const key = Symbol() const args = arguments[1] context[key] = this let result if(args) { result = context[key](...args) } else { result = context[key] } delete context[key] return result }
Function.prototype.myBind = function(context, ...args) { const fn = this const bindFn = function (...newFnArgs) { fn.call( this instanceof bindFn ? this : context, ...args, ...newFnArgs ) } bindFn.prototype = Object.create(fn.prototype) return bindFn }
const deepClone = (target, cache = new WeakMap()) => { if(target === null || typeof target !== 'object') { return target } if(cache.get(target)) { return target } const copy = Array.isArray(target) ? [] : {} cache.set(target, copy) Object.keys(target).forEach(key => copy[key] = deepClone(obj[key], cache)) return copy }
const debounce = (fn, wait = 300, leading = true) => { let timerId, result return function(...args) { timerId && clearTimeout(timerId) if (leading) { if (!timerId) result = fn.apply(this, args) timerId = setTimeout(() => timerId = null, wait) } else { timerId = setTimeout(() => result = fn.apply(this, args), wait) } return result } }
函數中止觸發後 n妙後開始執行,中止觸發後繼續執行一次事件 const throttle = (fn, wait = 300) => { let timerId return function(...args) { if(!timerId) { timerId = setTimeout(() => { timerId = null return result = fn.apply(this, ...args) }, wait) } } }
函數觸發後馬上執行,中止觸發後不在執行事件面試
const throttle = (fn, wait = 300) => { let prev = 0 let result return function(...args) { let now = +new Date() if(now - prev > wait) { prev = now return result = fn.apply(this, ...args) } } }
ES5的繼承,實質是先創造子類的實例對象,而後將再將父類的方法添加到this上。ES6的繼承,先創造父類的實例對象(因此必須先調用super方法,而後再用子類的構造函數修改this。編程
class Super { constructor(foo) { this.foo = foo } printFoo() { console.log(this.foo) } } class Sub extends Super { constructor(foo, bar) { super(foo) this.bar = bar } }js
上面做爲一部分都是做爲一個 P5應該具備基本技能,同時我這邊會陸續的更新一些列的面試題,對於 call、apply、bind 有什麼不清楚很差理解的地方能夠查看我以前的文章,讓你一篇文章完全搞清楚,這裏說了ES6繼承那麼後續我會結合面向對象編程和設計模式依次爲你們講解,關注 tu 老師說前端帶你玩轉全棧 設計模式