2016-12-30 93 views
0

我在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來處理這個問題的正確方法是什麼?有沒有更清潔或更強大的方法可以解決這個問題?

+3

我想你想調用的實際函數是在別的地方定義的?因爲實際上,只需將'this.property2 =「2」;'內聯即可。你問f.call(this)是否是調用函數並將'this'設置爲特定值的正確方法?如果是,那麼是的。 –

+0

@FelixKling我只是使用該函數作爲示例,我將用其他功能替換該代碼,這些功能會根據進入'Constructor'函數的參數改變對象。我將編輯這個問題來反映這個問題 –

回答

1

你在做什麼似乎有點無用的,因爲你可以直接使用

var Constructor = function(property2) { 
    this.property1 = "1"; 
    this.property2 = property2; 
}; 

但是,如果你的構造不復雜的事情,你想要的是他們分成部分爲更好的抽象,那麼我個人會採取這些外部零件,以便有一個更清潔的構造函數:

var Constructor = (function() { 
    function someLogic(instance, value) { 
    instance.property2 = value; 
    } 
    return function Constructor(property2) { 
    this.property1 = "1"; 
    someLogic(this, property2); 
    }; 
})(); 
+0

我編輯了我的問題,以反映我的構造函數會做更復雜的事情。謝謝 –

+0

不,你在任何編輯中都沒有說清楚函數會更復雜 –

+0

@GerardSimpson你做的唯一編輯就是給構造函數添加一個參數。這與你想要調用的複雜函數有什麼關係? – Barmar

相關問題