我正在创建一个库,其中包含一个每秒可能被调用数千次的函数。此函数需要 new
构造函数,以便将一组新数据绑定(bind)到固定原型(prototype),如下所示:
var internalFunc = function(a) {
this.foo = a;
};
internalFunc.prototype = {
something: 'some value',
anotherIndex: 'another value',
/* ... */
};
因此,我目前使用 new
构造函数调用 internalFunc
的方法是使用第二个函数,类似于所谓的“构造函数代理” '.
var funcThatGetsUsed = function( someArgument ){
return new internalFunc( someArgument );
};
但是,回到主要问题,这个 funcThatGetsUsed
每秒可以被调用数千次。因此,它可能会减小库的大小,并且如果我能够消除那个中间人“构造函数代理”功能,并且只需将新构造函数绑定(bind)到 internalFunc
,它就可以提高代码的速度>,可能与 bind
函数类似,如下所示:
var funcThatGetsUsed = internalFunc.bindToConstructor('new');
那么,有没有办法在 javascript 中使用 'bindToConstructor
' 来减少函数调用的开销?
请注意,我不能直接告诉库的用户使用 new 运算符的原因是因为那样会破坏这个特定库的目的。案例和要点:JQuery 使用“构造函数代理”函数。只需输入类似 console.log($.toString())
的内容,您应该会看到如下内容:
> console.log("'" + $.tostring() + "'")
'function (a,b){return new n.fn.init(a,b)}'
请注意,我的目标是 Edge 及更高版本,因此该解决方案不必在 Internet Explorer 中运行。我所说的“针对 Edge”的意思是,如果它在 Edge 中运行,那么它当然也可以在所有其他浏览器中运行。
最佳答案
您可以使用 Reflect.construct()
var funcThatGetsUsed = Reflect.contruct(internalFunc /* , [args] */ )
关于javascript - 将 'new' 构造函数“绑定(bind)”到 Javascript 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44146598/