'Binding' The 'new' Constructor To A Function In Javascript

247 Views Asked by At

I am creating a library with a function that might be called many thousands of times every second. This function requires the new constructor so as to bind a new set of data to a fixed prototype like so:

var internalFunc = function(a) {
   this.foo = a;
};
internalFunc.prototype = {
   something: 'some value',
   anotherIndex: 'another value',
   /* ... */
};

So, the way I am currently getting internalFunc to be called with a new constructor is by using a second function sort of like what one could call a 'constructor proxy'.

var funcThatGetsUsed = function( someArgument ){
     return new internalFunc( someArgument );
};

However, getting back to the main issue, this funcThatGetsUsed can get called many thousands of times a second. So, it might reduce the size of the library, and it could increase the speed of the code if I was able to eliminate that middle man 'constructor proxy' function, and just bind the new constructor to the internalFunc, maybe in a similar fashion to the bind function like so:

var funcThatGetsUsed = internalFunc.bindToConstructor('new');

So, is there a way to 'bindToConstructor' in javascript to reduce the function call overhead?

Please note that the reason for why I can't just tell the user of the library to use the new operator is because that would kind of defeat the purpose of this particular library. Case and point: JQuery uses a 'constructor proxy' function. Just type in something like console.log($.toString()), and you should see something like this:

> console.log("'" + $.tostring() + "'")

'function (a,b){return new n.fn.init(a,b)}'

Please note that I am targeting Edge and above, so the solution doesn't have to work in Internet Explorer. What I mean by 'targeting Edge' is that if it works in Edge, then it will, of course, work in every other browser.

1

There are 1 best solutions below

19
On

You can use Reflect.construct()

var funcThatGetsUsed = Reflect.contruct(internalFunc /* , [args] */ )