使新关键字可选

Dav*_*ing 6 javascript constructor new-operator javascript-objects

假设我要创建以下API:

var api = function(){}

api.prototype = {
  constructor: api,
  method: function() {
    return this;
  }
};
Run Code Online (Sandbox Code Playgroud)

现在,这将工作如下:

var myApi = new api();
myApi.method();
Run Code Online (Sandbox Code Playgroud)

但是,假设我想让new关键字成为可选的,这样就可以了:

api().method();
Run Code Online (Sandbox Code Playgroud)

我会出于自己的想法:

var api = function() {
  if ( !(this instanceof api) ) {
    return new api();
  }
};
Run Code Online (Sandbox Code Playgroud)

但我想知道,这可能会以某种方式轻易被感染,或者使用这种方法还有其他危险吗?我知道f.ex jQuery不会这样做(他们将构造函数卸载到原型方法),所以我确信有充分的理由不这样做.我只是不认识他们.

cui*_*ing 2

在构造函数中返回一个对象。

function Car(){
   var obj = Object.create(Car.prototype);
   obj.prop = 1;
   return obj;
}
Car.prototype = {
    method: function (){ }
};

//test
var car1 = Car();
var car2 = new Car();
Run Code Online (Sandbox Code Playgroud)