javascript - 在javascript中动态实例化类

标签 javascript class

我查看了这个reference link最终使用了 Matthew 的解决方案,因为它对我有用。

var factory ={};
factory.Tree = function(arg1,arg2,arg3,arg4){
    console.log(arg1+""+arg2+""+arg3+""+arg4); 
}
function instantiate(classname){
    return new (function(a){ return factory[classname].apply(this,a);})(Array.prototype.splice.call(arguments,1));
    // also is this ^^^ a good practice? instead of declaring the temp function beforehand
    // function t(a) {return factory[classname].apply(this,a);}
    // return new t(Array.prototype.splice.call(arguments,1));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 1234 --> works

不过,我不确定为什么使用 user123444555621 的解决方案只有在我传入“参数”(即包括“类名”的所有内容)时才有效:

function instantiate(classname){
    return new (Function.prototype.bind.apply(factory[classname], arguments));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 1234 --> works

但是如果我切片“参数”并删除“类名”,然后传入结果数组,它不会按预期工作:

function instantiate(classname){
    var args = Array.prototype.splice.call(arguments,1); 
        // ^^ I checked and this prints 1,2,3,4 as well
    return new (Function.prototype.bind.apply(factory[classname], args));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 234undefined

我不知道为什么,但不知何故,args 数组似乎被切片(再次)并删除了它的第一个元素(在本例中为 1)。

有人可以提供任何见解吗?谢谢

最佳答案

你使用了正确的数组函数吗slice vs splice

Array.prototype.slice() - Creates a new array from elements of an existing array. It does not modify the original array.

Array.prototype.splice() – Deletes and/or inserts elements in an array. Unlike slice(), the splice() method modifies the original array and returns a new array. The splice() method takes three arguments.

关于javascript - 在javascript中动态实例化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36661315/

相关文章:

javascript - Jquery id 到带有 freemarker 列表的 javascript 数组中

python - Python 中的元类和语法

c++ - 在 B 类中初始化 A 类(带有引用成员)

javascript - 使用字典对象动态绑定(bind) High-charts 中的系列

javascript - 如何使用 javascript 以编程方式编辑 HTML 格式的文本,而无需手动处理标签和 HTML

javascript - 在 iframe 中选择内容

c++ - 添加到动态数组

python - 在定义类的属性时进行强制转换?

c# - 覆盖嵌套类函数或使用委托(delegate)?**

javascript - 如何从数组中分割并获取选择数据