相关疑难解决方法(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万
查看次数

如何使用call或apply调用javascript构造函数?

我如何概括下面的函数来取N个参数?(使用电话或申请?)

是否有一种编程方式将参数应用于"新"?我不希望构造函数被视为普通函数.

/**
 * This higher level function takes a constructor and arguments
 * and returns a function, which when called will return the 
 * lazily constructed value.
 * 
 * All the arguments, except the first are pased to the constructor.
 * 
 * @param {Function} constructor
 */ 

function conthunktor(Constructor) {
    var args = Array.prototype.slice.call(arguments, 1);
    return function() {
        console.log(args);
        if (args.length === 0) {
            return new Constructor();
        }
        if (args.length === 1) {
            return new Constructor(args[0]);
        }
        if (args.length === …
Run Code Online (Sandbox Code Playgroud)

javascript call apply

82
推荐指数
4
解决办法
4万
查看次数

标签 统计

javascript ×2

apply ×1

call ×1

class ×1

constructor ×1

inheritance ×1

oop ×1