记录 —— 构造函数

129 阅读1分钟

如何保证构造函数必须与new一起使用

构造函数内部使用严格模式,即第一行加上use strict,这样忘记使用new命令就会报错
function Fubar(foo, bar) {
  use strict

  this._foo = foo;
  this._bar = bar;
}
构造函数内部判断是否使用new命令
function Fubar(foo, bar) {
  if (!(this instanceof Fubar)) {
    return new Fubar(foo, bar);
  }

  this._foo = foo;
  this._bar = bar;
}