Javascript 对象构造函数和设置属性

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;
        }
}

但是出于某种原因(想不出一个具体原因)我们只想或需要将参数作为构造函数的一部分,确保在创建新实例时设置它的最佳方法是什么对象类型?我想出的解决方案是简单地让属性匿名函数自我声明,但是在这种情况下,只要在 运行 次期间访问属性,"business logic" 就会重新 运行 这很傻。

 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 并省略参数的现实场景是什么在对象签名中不会是 pheasable

首先声明函数,然后在构造函数中使用它。

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);