2009-09-02 23 views
2

給定函數/類型聲明是這樣的:通過調用具有參數列表的構造函數來實例化對象使用apply?

function Person(name, ... other args ...){ 
    this.name 
    ... other init code ... 
} 

我想能夠調用的Person構造函數的參數數組被應用到它。我可以這樣做:

Person.apply(this, args) 

除了這不會實例化一個人,它只是將其稱爲一個函數。有什麼辦法,你把它用這種方式,但在「新」的情況下,即表現得像:

new Person(...) 
+0

Dup的:http://stackoverflow.com/questions/813383/how-can-i-construct-an-object-using-an-array-of -values-for-parameters-rather-tha – 2009-09-03 01:02:14

回答

1

原因:

var newInstance=Person.apply({}, args); 

您將應用構造空對象。但你應該意識到,這不會是真正的課堂實例。如果你想打賭類的實例,你應該把原型對象的克隆作爲第一個參數。

+0

我試過了,但不得不修改它才能正常工作: var newInstance = {}; Person.apply(newInstance,args); – airportyh 2009-09-02 17:54:07

1

關於這個before有相當長的來回。

總之,不,你不能這樣做,並讓它適用於所有情況。有一些非常有價值的代碼示例說明如何在該鏈接中完成它,但每個代碼都有一個破解的例子。但是,這對你來說可能已經足夠了。

+0

未接受此答案,因爲現在有一個很好的答案http://stackoverflow.com/questions/813383/how-can-i-construct-an-object-using-an-array-of-values-for-parameters -rather-tha#answer-813401 – airportyh 2010-11-10 18:28:43

相關問題