具有条件的Javascript对象属性

时间:2014-08-12 18:37:48

标签: javascript

如何在javascript中创建具有属性的对象?

类似的东西:

function translate() {
    this.city = function () {
        if (language == "English") {
            return "City";
        } else {
            return "Ville";
        }
    }
}

当我尝试使用它时:

translate.city

它返回undefined ......

1 个答案:

答案 0 :(得分:2)

您需要创建对象的实例:

var myTranslate = new translate();
var city = myTranslate.city();

或者,你可以这样做:

var translate = {
    city: function () {
        if (language == "English") {
            return "City";
        } else {
            return "Ville";
        }
    }
};
var city = translate.city();

如果您希望能够访问city属性而不将其作为函数调用并且您使用的是ES5或更高版本,则可以定义getter方法:

var translate = {};
Object.defineProperty(translate, "city", { 
    get: function () {
        if (language == "English") {
            return "City";
        } else {
            return "Ville";
        }
    }
});
console.log(translate.city);

或者另一种定义getter的方法(也需要ES5):

var translate = {
    get city() {
        if (language == "English") {
            return "City";
        } else {
            return "Ville";
        }
    }
};
console.log(translate.city);

还有一个变体(由@ vol7ron提供),它确定创建对象时的city值:

function Translate() {
    this.city = (function () {
        if (typeof language !== 'undefined' && language == "English") {
            return "City";
        } else {
            return "Ville";
        }
    }());
}

var translate = new Translate();
translate.city;  // "Ville"