防止漏写 new 而造成的构造函数执行异常

index.js

// 方法1:严格模式
function Person(name) {
  "use strict";
  this.name = name;
}

const lilei = Person("李雷"); // Error
console.log(lilei.name);

index.js

// 方法2:判断添加
function Person(name) {
  if (!(this instanceof Person)) {
    return new Person(...arguments);
  }
  this.name = name;
}

const lilei = Person("李雷");
console.log(lilei.name); // '李雷'

index.js

// 方法3:new.target
function Person(name) {
  if (!new.target) {
    return new Person(...arguments);
  }
  this.name = name;
}

const lilei = Person("李雷");
console.log(lilei.name); // '李雷'

posted on 2021-09-10 09:36  aisowe  阅读(39)  评论(0编辑  收藏  举报

导航