繁体   English   中英

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

但是由于某种原因(无法具体考虑),我们只是想要或需要将参数作为构造函数的一部分,确保在创建对象类型的新实例时对其进行设置的最佳方法是什么? 我想出的解决方案是简单地使属性匿名函数自声明,但是在这种情况下,只要在运行时访问属性,就会重新运行“业务逻辑”,这很愚蠢。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM