# JS 速查表

# 模拟new操作符

// EmuNew.js
function EmuNew (name){
  let obj = new Object() // 1
  Object.setPrototypeOf(obj, EmuNew.prototype); // 2
  // object.__proto__ = EmuNew.prototype; // 不推荐
  // let obj = Object.create(EmuNew.prototype); // 两步合并
  this = obj // 3
  this.name = name // 4
  return this // 5
}

# 寄生式组合继承

function SuperType(name) {
  this.name = name;
  this.colors = ["red", "green", "blue"];
}
SuperType.prototype.sayName = function () {};
function SubType(name, age) {
  SuperType.call(this, name);
  this.age = age;
}
SubType.prototype = Object.create(SuperType.prototype);
SubType.prototype.constructor = subType;
SubType.prototype.sayAge = function () {};

# 类继承

class SuperType {
  constructor(name) {
    this.name = name;
    this.colors = ["red", "green", "blue"];
  }
  sayName() {}
}
class SubType extends SuperType{
  constructor(name, age) {
    super();
    this.age = age;
  }
  sayAge() {};
}

# 高阶函数

function higherOrderFunction(func) {
    return func(5);
}

function multiplyByTen(num) {
    return num * 10;
}

console.log(higherOrderFunction(multiplyByTen)); // 50

# 闭包

function outerFunction() {
    let outerVariable = 'I am from outer function';

    function innerFunction() {
        console.log(outerVariable);
    }

    return innerFunction;
}

let closure = outerFunction();
closure(); // I am from outer function

# 函数柯里化

function curry(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      return function(...args2) {
        return curried.apply(this, args.concat(args2));
      }
    }
  };
}

# 装饰器模式

function decorator(func) {
    return function(...args) {
        console.log('Before function call');
        func.apply(this, args);
        console.log('After function call');
    };
}

function myFunction() {
    console.log('Inside myFunction');
}

let decoratedFunction = decorator(myFunction);
decoratedFunction(); // Before function call Inside myFunction After function call