Javascript 创建新的类实例并将参数作为数组应用
可能重复:Javascript 创建新的类实例并将参数作为数组应用,javascript,Javascript,可能重复: 我需要创建一个新的类(newsomeclass()),但我需要传递的参数是一个数组。我知道我可以使用apply()调用函数,并将参数数组作为第二个参数传递给apply,但在创建新实例时如何做到这一点 function myClass() { if(this instanceof arguments.callee) { init.apply(this, arguments); } function init() {
我需要创建一个新的类(
newsomeclass()
),但我需要传递的参数是一个数组。我知道我可以使用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);
希望我了解你需要什么,这一个可能会帮助你
希望我能理解你的需要,这本书可能会对你有所帮助。@JamesMontagne我无法让这个例子起作用。我得到这个错误:TypeError:Function.prototype.apply:Arguments列表有错误type@LordZardeck:你能告诉我们你正在尝试的代码吗。你确定你传递了一个数组吗?@JamesMontagne但我不能让这个例子起作用。我得到这个错误:TypeError:Function.prototype.apply:Arguments列表有错误type@LordZardeck:你能告诉我们你正在尝试的代码吗。你确定要传递数组吗?我不控制构造函数。你没有定义类/函数?我不控制构造函数。你没有定义类/函数?