相关疑难解决方法(0)

将.apply()与'new'运算符一起使用.这可能吗?

在JavaScript中,我想创建一个对象实例(通过new运算符),但是将任意数量的参数传递给构造函数.这可能吗?

我想做的是这样的事情(但下面的代码不起作用):

function Something(){
    // init stuff
}
function createSomething(){
    return new Something.apply(null, arguments);
}
var s = createSomething(a,b,c); // 's' is an instance of Something
Run Code Online (Sandbox Code Playgroud)

答案

从这里的回复中可以清楚地看出,没有内置的方式.apply()new运营商通话.然而,人们提出了一些非常有趣的解决方案.

我首选的解决方案是Matthew Crumley的这个解决方案(我已将其修改为通过该arguments属性):

var createSomething = (function() {
    function F(args) {
        return Something.apply(this, args);
    }
    F.prototype = Something.prototype;

    return function() {
        return new F(arguments);
    }
})();
Run Code Online (Sandbox Code Playgroud)

javascript oop inheritance constructor class

451
推荐指数
11
解决办法
7万
查看次数

使用.bind()避免使用.call()和.apply()

我正在寻找一种方法来完成某项任务,即从中走出来

jQuery.when.apply( null, promiseArray ).done(...)
Run Code Online (Sandbox Code Playgroud)

when( promiseArray ).done(...)
Run Code Online (Sandbox Code Playgroud)

您可能知道,.bind()可以习惯于创建类似默认参数的东西,也可以做一些非常漂亮的东西.例如,而不是总是打电话

var toStr = Object.prototype.toString;
// ...
toStr.call([]) // [object Array]
Run Code Online (Sandbox Code Playgroud)

我们可以这样做

var toStr = Function.prototype.call.bind( Object.prototype.toString );
toStr([]) // [object Array]
Run Code Online (Sandbox Code Playgroud)

这是相当酷的(即使有这样的性能调用.bind(),我知道并且我知道它),但我无法真正完成jQuerys .when调用.如果你有一个未知数量的promise对象,你通常将它们推入一个数组,然后就可以将它们传递到.when我上面的第一个代码片段中.

我到目前为止这样做:

var when = Function.prototype.apply.bind( $.when );
Run Code Online (Sandbox Code Playgroud)

现在我们可以去

when( null, promiseArray ).done(...)
Run Code Online (Sandbox Code Playgroud)

这有效,但我也想摆脱null每次都明确传入的需要.所以我试过了

var when = Function.prototype.apply.bind( $.when.call.bind( null ) );
Run Code Online (Sandbox Code Playgroud)

但那引起了我的注意:

"TypeError: Function.prototype.apply called on incompatible null"
Run Code Online (Sandbox Code Playgroud)

我想我现在坐在这已经太久了,不能再思考了.感觉就像有一个简单的解决方案.我不想使用任何额外的功能来解决这个问题,我绝对会优先使用解决方案.bind().

请在此处查看完整示例:http://jsfiddle.net/pp26L/

javascript jquery ecmascript-5

15
推荐指数
2
解决办法
2911
查看次数