将绑定应用与数组参数一起使用时参数丢失
Argument gets lost when using bind apply with array arguments
我使用 this answer here 通过使用以下代码传递数组参数来构造一个新的 class 实例:
new ( Cls.bind.apply( Cls, arguments ) )();
但是我的参数之一是一个数组,并且在构造过程中值丢失了
您可以查看演示此操作的示例 in this CodePen
在示例中我传递了第三个参数properties
:
var properties = [
{ name: "first", value: "1" },
{ name: "second", value: "2" },
{ name: "third", value: "3" }
];
但是结果中的属性是undefined
。
显然这里出了点问题,但是是什么以及为什么?
您的代码几乎是正确的,但您需要向 factory()
传递一个额外的参数:
factory(undefined, name, description, properties)
这在您 link 对问题的 SO 回答中突出显示:
The anything parameter doesn't matter much, since the new keyword resets f's context. However, it is required for syntactical reasons. Now, for the bind call: We need to pass a variable number of arguments, so this does the trick:
var f = Cls.bind.apply(Cls, [anything, arg1, arg2, ...]);
result = new f();
我使用 this answer here 通过使用以下代码传递数组参数来构造一个新的 class 实例:
new ( Cls.bind.apply( Cls, arguments ) )();
但是我的参数之一是一个数组,并且在构造过程中值丢失了
您可以查看演示此操作的示例 in this CodePen
在示例中我传递了第三个参数properties
:
var properties = [
{ name: "first", value: "1" },
{ name: "second", value: "2" },
{ name: "third", value: "3" }
];
但是结果中的属性是undefined
。
显然这里出了点问题,但是是什么以及为什么?
您的代码几乎是正确的,但您需要向 factory()
传递一个额外的参数:
factory(undefined, name, description, properties)
这在您 link 对问题的 SO 回答中突出显示:
The anything parameter doesn't matter much, since the new keyword resets f's context. However, it is required for syntactical reasons. Now, for the bind call: We need to pass a variable number of arguments, so this does the trick: var f = Cls.bind.apply(Cls, [anything, arg1, arg2, ...]); result = new f();