强制使用new模式

375 阅读1分钟

在日常工作中我们通常使用首字母大写来区分普通函数和构造函数,但构造函数仍然只是函数,如果在调用构造函数的时候忘记使用new,有可能导致逻辑错误或意外行为发生,所以推荐使用强制new模式。直接上代码:

function Person(name) {
  if (!(this instanceof Person)) {
    return new Person(name)
  }
  this.name = name
}
Person.prototype.getName = function () {
  return this.name
}

测试结果:
var first = new Person('michong'),
    second = Person('michong')
console.log(first.getName()) // michong
console.log(second.getName()) // michong
console.log(first instanceof Person) // true
console.log(second instanceof Person) // true

也可以使用ES6的Class语法糖,但是调用必须制定new 操作符,不然会报语法错误;

写在最后
本文摘抄自JavaScript模式,仅做笔记之用