JS 高级但开发时不常用的知识点

 8个月前     3  

文章目录

函数柯里化

函数柯里化(curry)是指将一个多参数的函数转化为多个单参数的函数。

最简实现

function curry(fn) {
   const  judge = (...args) =>
          args.length >= fn.length
              ? fn(...args)
              : (...arg) => judge(...args, ...arg)
    return judge
}

原理是这样的,JS 中可以通过函数的 length 获取函数的参数个数, curry 函数将 fn 包裹,返回一个函数。函数内部比较参数的长度,如果大于等于就执行 fn,否则就返回通过递归和闭包继续执行

实现 koa 类似的 compose 效果

const middleWare = []
middleWare.push(function (next) {
   console.log(1)
   next()
   console.log(2)
})
middleWare.push(function(next) {
   console.log(3)
   next()
   console.log(4)
})
middleWare.push(function(next) {
   console.log(5)
   next()
   console.log(6)
})
const fn = compose(middleWare)
fn() // 1,3,5,6,4,2

这个通过 js 执行的堆栈,进行循环即可

function compose(middleWare) {
  const fns = middleWare.slice(0)
  const next = function () {
    while(fns.length) {
      const fn = fns.shift()
      fn(next)
    }
  }
  return () => next()
}

ES5 实现继承的几种方式

1. 原型链模式

function SuperType() {
    this.color = [1,23,3]
}
function SubType() {}
SubType.prototype = new SuperType()

缺点:

  1. 引用属性共享
  2. 子类实例化时无法向父类传参

2. 盗用构造

function SuperType() {
    this.color = [1,23,3]
}
function SubType() {
    SuperType.call(this)
}

优点:

  1. 可给父类构造函数传递参数

缺点:

  1. 必须在构造函数种定义方法,函数不能重用
  2. 子类无法访问父类原型的方法

3. 组合继承

function SuperType() {
    this.color = [1,23,3]
}
function SubType() {
    SuperType.call(this)
}
SubType.prototype = new SuperType()

缺点: 父类的构造函数会被调用两次

4. 原型继承

Object.create()

function object(o) {
    function F() {}
    F.prototype = o
    return new F()
}

优点: 适合不需要单独创建构造函数
缺点: 同原型模式

5. 寄生构造

function createAnother(original) {
    let clone = Object.create(original)
    
    clone.sayHi = function(){}
    
    return clone
}

6. 寄生组合继承

function SuperType(name) {
    this.name = name
}
SuperType.prototype.sayName = function(){}

function SubType(name, age) {
    SuperType.call(this, name)
    this.age = age
}
function inheritPrototype(sub, super) {
    let prototype = Object.create(super.prototype)
    prototype.constructor = sub
    subType.prototype = prototype
}
inheritPrototype(SubType, SuperType)

Objec.create 原理

const b = Object.create(c)

Object.create 传入一个对象,返回一个对象,对象的__proto__ 指向 传入对象

b.__proto__ === c // true
b.isPrototypeOf(c) // true

因此 Object.create 的过程为

function objectCreate(c) {
  const b = {}
  b.__proto__ = c
  return b
}

new 的过程

function customNew(A,...args) {
     const a = {}
     const ret = A.call(a,...args)
     a.__proto__ = A.prototype
     return  (ret &&  typeof ret === 'object' ) ? ret :  a
}

一图理解原型链

JS 高级但开发时不常用的知识点

暂无评论

暂无评论...