如何在 JavaScript 中使用参数值数组构造对象,而不是将它们列出来? [英] How can I construct an object using an array of values for parameters, rather than listing them out, in JavaScript?

查看:16
本文介绍了如何在 JavaScript 中使用参数值数组构造对象,而不是将它们列出来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?我正在创建一个单一的基础工厂函数来驱动不同类型的工厂(但有一些相似之处),我希望能够将参数作为数组传递给基础工厂,然后可能会创建一个新对象的实例来填充参数相关类的构造函数通过数组.

Is this possible? I am creating a single base factory function to drive factories of different types (but have some similarities) and I want to be able to pass arguments as an array to the base factory which then possibly creates an instance of a new object populating the arguments of the constructor of the relevant class via an array.

在 JavaScript 中,可以通过 apply 方法使用数组来调用具有多个参数的函数:

In JavaScript it's possible to use an array to call a function with multiple arguments by using the apply method:

namespace.myFunc = function(arg1, arg2) { //do something; }
var result = namespace.myFunc("arg1","arg2");
//this is the same as above:
var r = [ "arg1","arg2" ];
var result = myFunc.apply(namespace, r);

不过,似乎没有办法使用 apply 创建对象的实例,是吗?

It doesn't seem as if there's anyway to create an instance of an object using apply though, is there?

类似的东西(这不起作用):

Something like (this doesn't work):

var instance = new MyClass.apply(namespace, r);

推荐答案

试试这个:

var instance = {};
MyClass.apply( instance, r);

关键字new"所做的就是将一个新对象传递给构造函数,然后它成为构造函数内部的 this 变量.

All the keyword "new" does is pass in a new object to the constructor which then becomes the this variable inside the constructor function.

根据构造函数的编写方式,您可能必须这样做:

Depending upon how the constructor was written, you may have to do this:

var instance = {};
var returned = MyClass.apply( instance, args);
if( returned != null) {
    instance = returned;
}

更新:评论说如果有原型,这将不起作用.试试这个.

Update: A comment says this doesn't work if there is a prototype. Try this.

function newApply(class, args) {
    function F() {
        return class.apply(this, args);
    }
    F.prototype = class.prototype;
    return new F();
}

newApply( MyClass, args);

这篇关于如何在 JavaScript 中使用参数值数组构造对象,而不是将它们列出来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆