创建对象并设置属性

时间:2014-10-27 17:18:29

标签: javascript oop

使用以下对象作为示例

var CarAd = function(car){
 this.year = car.year;
 this.model = car.model;
 this.make = car.make;
 this.formattedDescription = function(){
   return "this is a " + this.year + " " + this.make + " " + this.model;
 }
}

我希望在实例化对象时可以使用formattedDescription的值,但就其而言,formattedDescription()当然在执行之前不会执行。如何重构?

3 个答案:

答案 0 :(得分:0)

我不知道它是不是hacky,但你可以自动调用该函数并将其值赋值给formattedDescription。

var CarAd = function(car){
 this.year = car.year;
 this.model = car.model;
 this.make = car.make;
 this.formattedDescription = (function(){
   return "this is a " + this.year + " " + this.make + " " + this.model;
 })()
}

编辑......这感觉更自然:

var CarAd = function(car){
 this.year = car.year;
 this.model = car.model;
 this.make = car.make;
 function createFormattedDescription () {
   return "this is a " + this.year + " " + this.make + " " + this.model;
 };
 this.formattedDescription = createFormattedDescription();
}

答案 1 :(得分:0)

this.formattedDescription作为自执行的函数,如:

this.formattedDescription = (function(){
   return "this is a " + this.year + " " + this.make + " " + this.model;
 })();

答案 2 :(得分:0)

可以这么简单:

var makecar = function(year, model, make){
    return {
        year: year,
        model: model,
        make: make,
        description: "this is a " + year + " " + make + " " + model
    };
};