preface

In view of the current common interview questions, this paper only provides the corresponding core principles and ideas, and some boundary details are not dealt with. The follow-up will continue to update, I hope to help you.

1. Implement a call function

// Thread: Attach the method this points to to the target this and return
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)
  letresult = context.fn(... arg)delete context.fn
  return result
} 
Copy the code

2. Implement an apply function

// Thread: Attach the method this points to to the target this and return
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
}
Copy the code

Implement a bind function

// Call is similar to call, but returns a function
Function.prototype.mybind = function (context) {
  if (typeof this! = ='function') {
    throw new TypeError('Error')}let _this = this
  let arg = [...arguments].slice(1)
  return function F() {
    // Handle the case where the function uses new
    if (this instanceof F) {
      return new_this(... arg, ... arguments) }else {
      return_this.apply(context, arg.concat(... arguments)) } } }Copy the code

4. How instanceof works

// The prototype of the right variable exists in the prototype chain of the left variable
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__
  }
}
Copy the code

5. Basic implementation principle of Object. Create

// Use the object passed in as a prototype
function create(obj) {
  function F() {}
  F.prototype = obj
  return new F()
}
Copy the code

6. New nature

function myNew (fun) {
  return function () {
    // Create a new object and point its implicit stereotype to the constructor stereotype
    let obj = {
      __proto__ : fun.prototype
    }
    // Execute the constructorfun.call(obj, ... arguments)// Return this object
    return obj
  }
}

function person(name, age) {
  this.name = name
  this.age = age
}
let obj = myNew(person)('chen'.18) // {name: "chen", age: 18}
Copy the code

7. Make a basic Promise

// No additional boundary cases such as asynchronous processing are added
// then
class Promise {
  constructor (fn) {
    // Three states
    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
      }
    }
    // Automatically execute the function
    try {
      fn(resolve, reject)
    } catch (e) {
      reject(e)
    }
  }
  // then
  then(onFulfilled, onRejected) {
    switch (this.state) {
      case 'fulfilled':
        onFulfilled()
        break
      case 'rejected':
        onRejected()
        break
      default:}}}Copy the code

8. Implement shallow copy

/ / 1.... implementation
letcopy1 = {... {x:1}}

// 2. object. assign implementation

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

9. Implement a basic deep copy

// 1. JOSN.stringify()/JSON.parse()
let obj = {a: 1.b: {x: 3}}
JSON.parse(JSON.stringify(obj))

// 2. Recursive copy
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
}
Copy the code

10. Use setTimeout to simulate setInterval

// To avoid inconsistent setInterval execution times
setTimeout (function () {
  // do something
  setTimeout (arguments.callee, 500)},500)
Copy the code

11.js implements an inheritance method

// Borrow the constructor to inherit the instance attributes
function Child () {
  Parent.call(this)}// The parasite inherits the stereotype attributes
(function () {
  let Super = function () {}
  Super.prototype = Parent.prototype
  Child.prototype = new Super()
})()
Copy the code

12. Implement a basic Event Bus

// Component communication, a process that triggers and listens
class EventEmitter {
  constructor () {
    // Store events
    this.events = this.events || new Map()}// Listen on events
  addListener (type, fn) {
    if (!this.events.get(type)) {
      this.events.set(type, fn)
    }
  }
  // Trigger the event
  emit (type) {
    let handle = this.events.get(type)
    handle.apply(this, [...arguments].slice(1))}}/ / test
let emitter = new EventEmitter()
// Listen on events
emitter.addListener('ages', age => {
  console.log(age)
})
// Trigger the event
emitter.emit('ages'.18)  / / 18
Copy the code

13. Implement a two-way data binding

let obj = {}
let input = document.getElementById('input')
let span = document.getElementById('span')
// Data hijacking
Object.defineProperty(obj, 'text', {
  configurable: true.enumerable: true,
  get() {
    console.log('Got the data')
  },
  set(newVal) {
    console.log('Data updated')
    input.value = newVal
    span.innerHTML = newVal
  }
})
// Input listener
input.addEventListener('keyup'.function(e) {
  obj.text = e.target.value
})
Copy the code

The full implementation is available before: this is probably the most detailed explanation of responsive systems yet

14. Implement a simple route

/ / hash routing
class Route{
  constructor() {// Route storage object
    this.routes = {}
    / / the current hash
    this.currentHash = ' '
    // bind this to avoid this pointing to change when listening
    this.freshRoute = this.freshRoute.bind(this)
    / / to monitor
    window.addEventListener('load'.this.freshRoute, false)
    window.addEventListener('hashchange'.this.freshRoute, false)}/ / store
  storeRoute (path, cb) {
    this.routes[path] = cb || function () {}}/ / update
  freshRoute () {
    this.currentHash = location.hash.slice(1) | |'/'
    this.routes[this.currentHash]()
  }   
}
Copy the code

15. Implement lazy loading

<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>
Copy the code
let imgs =  document.querySelectorAll('img')
// Viewable height
let clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
function lazyLoad () {
  // Roll off the height
  let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  for (let i = 0; i < imgs.length; i ++) {
    // The height of the image in the viewable area
    let x = clientHeight + scrollTop - imgs[i].offsetTop
    // The image is in the viewable area
    if (x > 0 && x < clientHeight+imgs[i].height) {
      imgs[i].src = imgs[i].getAttribute('data')}}}// addEventListener('scroll', lazyLoad) or setInterval(lazyLoad, 1000)
Copy the code

16. Rem basic Settings

// Original configuration
function setRem () {
  let doc = document.documentElement
  let width = doc.getBoundingClientRect().width
  let rem = width / 75
  doc.style.fontSize = rem + 'px'
}
// Listen for window changes
addEventListener("resize", setRem)
Copy the code

17. Implement AJAX by hand

// 1. Simple process

/ / instantiate
let xhr = new XMLHttpRequest()
/ / initialization
xhr.open(method, url, async)
// Send the request
xhr.send(data)
// Set the status change callback to process the request result
xhr.onreadystatechange = (a)= > {
  if (xhr.readyStatus === 4 && xhr.status === 200) {
    console.log(xhr.responseText)
  }
}

// 2. Implement based on promise

function ajax (options) {
  // Request an address
  const url = options.url
  // Request method
  const method = options.method.toLocaleLowerCase() || 'get'
  // The default is asynchronous true
  const async = options.async
  // Request parameters
  const data = options.data
  / / instantiate
  const xhr = new XMLHttpRequest()
  // The request timed out
  if (options.timeout && options.timeout > 0) {
    xhr.timeout = options.timeout
  }
  // Return a Promise instance
  return new Promise ((resolve, reject) = > {
    xhr.ontimeout = (a)= > reject && reject('Request timed out')
    // Listen for state change callbacks
    xhr.onreadystatechange = (a)= > {
      if (xhr.readyState == 4) {
        If the value ranges from 200 to 300, the request is successful, and 304 resources remain unchanged
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
          resolve && resolve(xhr.responseText)
        } else {
          reject && reject()
        }
      }
    }
    // Error callback
    xhr.onerror = err= > reject && reject(err)
    let paramArr = []
    let encodeData
    // Process request parameters
    if (data instanceof Object) {
      for (let key in data) {
        // Parameter concatenation is encoded by encodeURIComponent
        paramArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
      }
      encodeData = paramArr.join('&')}// get request concatenation parameters
    if (method === 'get') {
      // Check whether the url already exists. And their locations
      const index = url.indexOf('? ')
      if (index === - 1) url += '? '
      else if(index ! == url.length- 1) url += '&'
      / / stitching url
      url += encodeData
    }
    / / initialization
    xhr.open(method, url, async)
    // Send the request
    if (method === 'get') xhr.send(null)
    else {
      // Post requires a request header
      xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded; charset=UTF-8')
      xhr.send(encodeData)
    }
  })
}
Copy the code

18. Implement drag and drop

window.onload = function () {
  // Drag is in absolute position
  let drag = document.getElementById('box')
  drag.onmousedown = function(e) {
    var e = e || window.event
    // Distance between the mouse and the drag element boundary = distance between the mouse and the viewable area boundary - distance between the drag element and the boundary
    let diffX = e.clientX - drag.offsetLeft
    let diffY = e.clientY - drag.offsetTop
    drag.onmousemove = function (e) {
      // The distance the drag element moves = the distance between the mouse and the viewable area - the distance between the mouse and the drag element
      let left = e.clientX - diffX
      let top = e.clientY - diffY
      // Avoid dragging out of viewable area
      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}}}Copy the code

Implement a throttling function

// Only trigger once in a specified time
function throttle (fn, delay) {
  // Use closures to save time
  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('the throttling')
}
addEventListener('scroll', throttle(fn, 1000)) 
Copy the code

20. Implement an anti-shake function

// Do not trigger the second time within the specified time
function debounce (fn, delay) {
  // Use closures to save timers
  let timer = null
  return function () {
    let context = this
    let arg = arguments
    // If the timer is triggered again within the specified time, the timer will be cleared and then reset
    clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(context, arg)
    }, delay)
  }
}

function fn () {
  console.log('if you')
}
addEventListener('scroll', debounce(fn, 1000)) 
Copy the code

The last

Updates will continue in the future, welcome to focus on a thumbs-up!