[英]Javascript object constructor and setting properties
在這樣的情況下,當我們有一個對象時,
Object1 = function(param1){
this.attribute1=function(param1){
console.log("executing");
//random business logic could be anything
var newRelationship;
switch (param1){
case "epic": newRelationship= new Epic([this.startPoint, this.endPoint]);
break;
case "lame": newRelationship = "lamest";
break;
}
console.log(newRelationship);
return newRelationship;
}
}
對象屬性實際上不會在構造函數調用上設置,例如var moveCircle = new Object1("epic)
,這意味着,如果任何其他屬性都依賴於該一個對象屬性,那么我們將遇到一些問題。
一種解決方案是實現一個setter並在對象構造之后立即調用它,以設置我們的屬性,但是,這意味着在對象構造函數簽名中不需要該參數。
Object1 = function(){
this.attribute1=""
this.setAttribute1 = function(param1){
console.log("executing");
//random business logic could be anything
var newRelationship;
switch (param1){
case "epic": newRelationship= new Epic([this.startPoint, this.endPoint]);
break;
case "lame": newRelationship = "lamest";
break;
}
console.log(newRelationship);
this.attribute1 = newRelationship;
}
}
但是由於某種原因(無法具體考慮),我們只是想要或需要將參數作為構造函數的一部分,確保在創建對象類型的新實例時對其進行設置的最佳方法是什么? 我想出的解決方案是簡單地使屬性匿名函數自聲明,但是在這種情況下,只要在運行時訪問屬性,就會重新運行“業務邏輯”,這很愚蠢。
Object1 = function(param1){
this.attribute1=function(param1){
console.log("executing");
//random business logic could be anything
var newRelationship;
switch (param1){
case "epic": newRelationship= new Epic([this.startPoint, this.endPoint]);
break;
case "lame": newRelationship = "lamest";
break;
}
console.log(newRelationship);
return newRelationship;
}
}()
有人可以告訴我解決該問題的最佳方法是什么,什么是常見實踐,以及在哪種現實情況下使用設置器並忽略對象簽名中的參數是不可行的?
首先聲明函數,然后在構造函數中使用它。
Object1 = function(param1){ function foo(param1){ console.log("I am called only once!"); //random business logic could be anything var newRelationship; switch (param1){ case "epic": newRelationship = "epic"; break; case "lame": newRelationship = "lamest"; break; } console.log(newRelationship); return newRelationship; } this.attribute1 = foo(param1); } var obj = new Object1('epic'); obj.attribute1; obj.attribute1; obj.attribute1; obj.attribute1; obj.attribute1; obj.attribute1; console.log(obj.attribute1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.