nmsn / blog

记录日常遇到的问题,需要记录的笔记以及新学到的知识,会进行汇总和分类,自动更新 README,欢迎评论和补充,互相学习
36 stars 0 forks source link

ES6 Class #6

Open nmsn opened 2 years ago

nmsn commented 2 years ago
  1. https://github.com/xiaohesong/TIL/blob/master/front-end/es6/understanding-es6/class.md
  2. https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/20
nmsn commented 2 years ago

es6 class 和 es5 构造函数的区别

  1. class 声明会进入暂时性死区,提前调用会报错
  2. class 内部会启用严格模式
  3. class 的所有方法不可枚举
  4. class 的所有方法(包括静态方法和实例方法)都没有原型对象,所以也没有 [[construct]],不能使用 new 来实例化
  5. 必须使用 new 调用 class
  6. class 内部无法重写类名
nmsn commented 2 years ago

babel 编译 class 的结果

// es6
class Person {
    constructor(name) {
        this.name = name
    }

  sayName() {
    return this.name;
  }
}

// es5
function _instanceof(left, right) {
  if (
    right != null &&
    typeof Symbol !== "undefined" &&
    right[Symbol.hasInstance]
  ) {
    return !!right[Symbol.hasInstance](left);
  } else {
    return left instanceof right;
  }
}

function _classCallCheck(instance, Constructor) {
  if (!_instanceof(instance, Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  Object.defineProperty(Constructor, "prototype", { writable: false });
  return Constructor;
}

var Person = /*#__PURE__*/ (function () {
  function Person(name) {
    _classCallCheck(this, Person);

    this.name = name;
  }

  _createClass(Person, [
    {
      key: "sayName",
      value: function sayName() {
        return this.name;
      },
    },
  ]);

  return Person;
})();