创建新的类实例并将参数应用为数组

creating new class instance and applying arguments as array

本文关键字:参数 应用 数组 实例 创建      更新时间:2023-09-26

可能的重复项:
将 .apply() 与 'new' 运算符一起使用。这可能吗?

我需要创建一个类(new SomeClass())的新坚持,但我需要传递的参数是一个数组。我知道我可以使用apply()调用函数并将参数数组作为第二个参数传递给apply,但是在创建新实例时如何执行此操作?

function ​myClass​()
{
    if(this instanceof arguments.callee)
    {
        init.apply(this, arguments);
    }
    function init()
    {
        this.args=arguments;
        console.log(arguments);
    }
}
var myArray=[1,2,3];
var obj=new myClass(myArray);
console.log(obj.args);

这里的例子。希望我了解您的需求,而这个可能会对您有所帮助。