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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With