Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the new keyword optional

Say I want to create the following API:

var api = function(){}

api.prototype = {
  constructor: api,
  method: function() {
    return this;
  }
};

Now, this will work like:

var myApi = new api();
myApi.method();

But let’s say I want to make the new keyword optional, so that this will work:

api().method();

I would out of my head do:

var api = function() {
  if ( !(this instanceof api) ) {
    return new api();
  }
};

But I was wondering, could this easily be infected somehow, or are there other dangers around using this method? I know that f.ex jQuery don’t do this (they offload the constructor to a prototype method), so I’m sure there are good reason for not doing this. I just don’t know them.

like image 972
David Hellsing Avatar asked Nov 08 '12 00:11

David Hellsing


1 Answers

return an object in the constructor function.

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();
like image 181
cuixiping Avatar answered Oct 18 '22 19:10

cuixiping