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

时间:2015-12-14 11:30:15

标签: javascript oop constructor getter-setter

在这样的场景中,当我们有一个对象时,

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并省略对象签名中的参数的现实场景是不可行的

1 个答案:

答案 0 :(得分:1)

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



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