前端面接でよく見かける手書きのテーマ


1.手ぶれ防止を実現する
function debounce(fn,delay = 200){
     
  if(typeof fn !== 'function'){
     
    throw new TypeError('fn is not a function')
  }
  let lastFn = null;
  return function(...args){
     
    if(lastFn) clearTimeout(lastFn)
    lastFn = setTimeout(()=>{
     
      fn.call(this,...args)
    },delay)
  }
}

function clickHandle(){
     
  console.log('test')
}

window.onscroll = debounce(clickHandle,500)
2.アースフローの実現
function throttle(fn,delay = 200){
     
  if(typeof fn !== 'function'){
     
    throw new TypeError('fn is not a function')
  }
  let flag = null;
  return function(...args){
     
    if(!flag){
     
      setTimeout(()=>{
     
        flag = true
        fn.call(this,...args)
      },delay)
    }
  }
}
function clickHandle(){
     
  console.log('test')
}

window.onscroll = debounce(clickHandle,500)
3.bindを実現する
Function.prototype.bind = function(obj,arg){
     
  let arg = Array.prototype.slice.call(arguments,1)
  let _this = this
  let obj = function(newArg){
     
    arg = arg.concat( Array.prototype.slice.call(newArg))
    return content.apply(obj,arg)
  }
  obj.prototype = Object.create(_this.prototype)
  return obj
}
4.new内部原理(new Part()
function myNew(){
     
  let obj = {
     }
  obj.__proto__ = Parent.prototype
  Parent.call(obj)
  return obj
}
5.関数コリック化
  • ここで実行されるとFunctionですので、実際の効果はありません.
    function add(){
         
      let args = Array.from(arguments)
      let _adder = function(){
         
        args.push(...arguments)
        return _adder
      }
    
      _adder.toString = function(){
         
         return _args.reduce(function (a, b) {
         
                return a + b;
            });
      }
      return _adder
    }
    console.log(add(1,2)(2))