【发布时间】:2015-12-14 11:30:15
【问题描述】:
在这样的场景中,当我们有一个对象时,
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;
}
}()
有人能告诉我解决这个问题的最佳方法是什么吗?常见做法是什么?在哪些现实场景中使用 setter 并在对象签名中省略参数是不可行的
【问题讨论】:
标签: javascript oop constructor getter-setter