ES6规范

const 标识常量

const START = "start";
const RADOMEOBJ = {
  a: "A",
  b: "B",
};

1.const不允许重复声明赋值

var args = "test"; //var可以重复声明赋值
// var args = "change";

//通过数据劫持,可以不允许重复声明赋值
Object.defineProperty(window, "args", {
  // value: "change",
  writable: false,
});
args = "test2";
// console.log(args); //test

const args2 = "args2"; //不允许重复声明赋值
// args2 = "args3"; //报错:Uncaught TypeError: Assignment to constant variable.
  1. 块级作用域
if (true) {
  console.log(args1); //undefined
  var args1 = "args1";
}

if (true) {
  console.log(args1); //报错:Uncaught ReferenceError: Cannot access 'args1' before initialization
  const args1 = "args1";
}

3.const 和 let

const obj = {
  name: "Jon",
  age: 18,
};
obj.age = 20;
console.log(obj.age); //20 使用const定义对象,也会改变(对象是引用类型)

如何对一个对象进行常量化?

Object.freeze(obj);
obj.name = "Mary";
console.log(obj.name); //Jon 但只能对根层常量化

const obj2 = {
  name: "Jon",
  age: 18,
  favo: {
    type: 1,
    playName: "LOL",
  },
};
Object.freeze(obj2);
obj2.favo.playName = "Game";
console.log(obj2.favo.playName); //Game

解决只能对根层常量化

function deepFreeze(obj) {
  Object.freeze(obj);
  (Object.keys(obj) || []).forEach((key) => {
    if (typeof obj[key] == "object") {
      deepFreeze(obj[key]);
    }
  });
}
deepFreeze(obj2);
obj2.favo.playName = "Game";
console.log(obj2.favo.playName); //LOL

deconstruction 解构

const person = {
  name: "Mark",
  age: 20,
};
const { name: perName, age: perAge } = person;

let a = 1;
let b = 2;
[b, a] = [a, b];

箭头函数

const test = (a, b) => a + b;
const test2 = (x) => {};

1.上下文

const animal = {
  name: "dog",
  age: 2,
  running: function () {
    console.log(`${this.name} is running`);
  },
  eat: () => {
    // 不存在独立上下文
  },
};

2.箭头函数在什么情况下不能使用

//监听dom操作
const btn = document.querySelector("#btn");
btn.addEventListener("click", function () {
  this.style.color = "#fff";
});

//类操作的时候
// 箭头函数无法去构造类
function Obj(teacher, leader) {
  this.teacher = teacher;
  this.leader = leader;
}
const Obj = (teacher, leader) => {
  this.teacher = teacher;
  this.leader = leader;
};

//箭头函数的参数特性 - 不要在箭头函数里使用arguments
const test = function(teacher) {
  // arguments
}
const test2 = teacher => {}

class 类

function CountDown(ramainTime, step) {
  this.ramainTime = ramainTime;
  this.step = step;
}
CountDown.prototype.getTime = function () {
  return `${this.ramainTime}`;
};
const countDown = new CountDown(Date.now(), 1000);
countDown.getTime();

//es6
class CountDown {
  constructor(ramainTime, step) {
    this.ramainTime = ramainTime;
    this.step = step;
  }
  getTime() {
    return "";
  }
  static calcTime() {}
}

const countDown2 = new CountDown(Date.now(), 1000);
countDown2.getTime();
CountDown.calcTime();

class 的类型是: Function=>Object=>null
class的prototype: CountDown.prototype
class 函数对象的属性: countDown2.hasOwnProperty(‘step’)

如何建立只读变量

class Game {
  constructor(name) {
    // this._name = name;
    // this.level = 5;

    /**2.通过let */
    let _level = 6;
    this.getLevel = () => {
      return _level;
    };
  }
  /*1.可以通过get方式*/
  // get name() {
  //   return this._name;
  // }
}
const game = new Game("LOL");
// console.log(game.name);
console.log(game.getLevel());

封装核心 - 适配器模式

// {
//     name: {
//         value: 'lodash',
//         tag: 124,
//         name: 'es6'
//     }
// }
class utils {
  constructor(core) {
    this._main = core;
    this._name = "_";
  }
  get name() {
    return {
      ...this._main.name,
      name: `${this._name}`,
    };
  }
  set name(val) {
    this._name = val;
  }
}

Promise(手写promise)

const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';

class Promise {
  constructor(executor) {
    // 1. 默认状态 - PENDING
    this.status = PENDING;
    // 2. 内部维护的变量值
    this.value = undefined;
    this.reason = undefined;
    // 3. 存放回调
    this.onResolvedCallbacks = [];
    this.onRejectedCallbacks = [];

    // 成功的回调
    let resolve = value => {
      // 单向流转
      if (this.status === PENDING) {
        this.status = FULFILLED;
        this.value = value;
        this.onResolvedCallbacks.forEach(fn => fn());
      }
    };

    // 失败的回调
    let reject = reason => {
      // 单向流转
      if (this.status === PENDING) {
        this.status = REJECTED;
        this.reason = reason;
        this.onRejectedCallbacks.forEach(fn => fn());
      }
    };

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  then(onFulfilled, onRejected) {
    // 4. 处理默认参数
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };

    // 5. 链式调用
    let promise2 = new Promise((resolve, reject) => {
      if (this.status === FULFILLED) {
        // 6. 异步执行
        setTimeout(() => {
          try {
            let x = onFulfilled(this.value);
            this.resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      }
      if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = onRejected(this.reason);
            this.resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      }
      if (this.status === PENDING) {
        // 存放队列
        this.onResolvedCallbacks.push(() => {
          setTimeout(() => {
            try {
              let r = onFulfilled(this.value);
              this.resolvePromise(promise2, r, resolve, reject);
            } catch (error) {
              reject(error);
            }
          }, 0);
        });
        this.onRejectedCallbacks.push(() => {
          setTimeout(() => {
            try {
              let r = onRejected(this.reason);
              this.resolvePromise(promise2, r, resolve, reject);
            } catch (error) {
              reject(error);
            }
          }, 0);
        });
      }
    });

    return promise2;
  }

  resolvePromise(promise2, x, resolve, reject) {
    // 7. 判断 x 和 promise2 是否相同
    if (promise2 === x) {
      return reject(new Error('error'));
    }

    // 8. 判断 x 的类型
    let rc = false;
    if (x instanceof Promise) {
      x.then(value => {
        this.resolvePromise(promise2, value, resolve, reject);
      }, reason => {
        reject(reason);
      });
    } else if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
      try {
        let then = x.then;
        if (typeof then === 'function') {
          then.call(x, value => {
            if (!rc) {
              rc = true;
              this.resolvePromise(promise2, value, resolve, reject);
            }
          }, reason => {
            if (!rc) {
              rc = true;
              reject(reason);
            }
          });
        } else {
          resolve(x);
        }
      } catch (error) {
        if (!rc) {
          rc = true;
          reject(error);
        }
      }
    } else {
      resolve(x);
    }
  }

  static resolve(value) {
    return new Promise((resolve, reject) => {
      resolve(value);
    });
  }

  static reject(reason) {
    return new Promise((resolve, reject) => {
      reject(reason);
    });
  }

  static all(promises) {
    return new Promise((resolve, reject) => {
      let count = 0;
      let result = [];
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(value => {
          count++;
          result[i] = value;
          if (count === promises.length) {
            resolve(result);
          }
        }, reason => {
          reject(reason);
        });
      }
    });
  }

  static race(promises) {
    return new Promise((resolve, reject) => {
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(value => {
          resolve(value);
        }, reason => {
          reject(reason);
        });
      }
    });
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值