当我想在javascript中使用从其他地方提供的参数调用函数时,我可以使用apply函数的方法,如:
array = ["arg1", 5, "arg3"]
...
someFunc.apply(null, array);
Run Code Online (Sandbox Code Playgroud)
但是如果我需要以类似的方式调用构造函数呢?这似乎不起作用:
array = ["arg1", 5, "arg3"]
...
someConstructor.apply({}, array);
Run Code Online (Sandbox Code Playgroud)
至少不是我在尝试:
template = ['string1', string2, 'etc'];
var resultTpl = Ext.XTemplate.apply({}, template);
Run Code Online (Sandbox Code Playgroud)
这不起作用:
Ext.XTemplate.prototype.constructor.apply({}, template);
Run Code Online (Sandbox Code Playgroud)
有什么办法使这个工作吗?(在这个特殊情况下,我发现它new Ext.XTemplate(template)会起作用,但我对一般情况感兴趣)
类似的问题,但特定于内置类型,没有我可以使用的答案: 通过调用prototype.constructor.apply实例化JavaScript对象
谢谢.
时间已经过去,ES6和转换器现在已成为一件事.在ES6中,做我想做的事是微不足道的:new someConstructor(...array).
Babel会将其转换为ES5 new (Function.prototype.bind.apply(someConstructor, [null].concat(array)))();,如何构建JavaScript对象(使用'apply')中进行了解释?.
我们正在使用Eclipse保存操作来删除尾随的空白区域,组织导入和一些基本的代码格式.这并非总是如此,而且当我们编辑文件时,项目非常庞大和老旧,我们得到了许多与提交无关的源代码控制更改.我们经常做的是我们提交格式而不单独更改代码,然后代码更改.
能够在我们的项目中的每个Java文件上运行保存操作然后一劳永逸地提交它将是非常方便的,但我还没有找到一种方法来做到这一点.怎么能实现这一目标?
我发现这段代码的行为令人费解,为什么构造函数child不是Child?有人可以向我解释一下吗?
function Parent() {
this.prop1 = "value1";
this.prop2 = "value2";
}
function Child() {
this.prop1 = "value1b";
this.prop3 = "value3";
}
Child.prototype = new Parent();
var child = new Child();
// this is expected
console.log(child instanceof Child); //true
console.log(child instanceof Parent); //true
// what??
console.log(child.constructor == Child); //false
console.log(child.constructor == Parent); //true
Run Code Online (Sandbox Code Playgroud)