我在JavaScript中使用構造函數實例化一個對象實例化。像這樣:的Javascript調用構造函數時一次的對象與新
var Constructor = function(){
this.property1 = "1";
}
var child = new Constructor();
console.log(child) // Constructor {property1: "1"}
我想每當child
對象通過new
關鍵字實例化被調用一次的方法。我希望此方法僅適用於Constructor
。
這是我想出迄今:
var Constructor = function(property2){
this.property1 = "1";
(function(){ this.property2 = property2}).call(this);
}
var child = new Constructor("2")
console.log(child) // Constructor {property1: "1", property2: "2"}
這是在Javascript來處理這個問題的正確方法是什麼?有沒有更清潔或更強大的方法可以解決這個問題?
我想你想調用的實際函數是在別的地方定義的?因爲實際上,只需將'this.property2 =「2」;'內聯即可。你問f.call(this)是否是調用函數並將'this'設置爲特定值的正確方法?如果是,那麼是的。 –
@FelixKling我只是使用該函數作爲示例,我將用其他功能替換該代碼,這些功能會根據進入'Constructor'函數的參數改變對象。我將編輯這個問題來反映這個問題 –