Vinc 웃
Vinc 웃

Reputation: 1247

Javascript Object Properties with condition

How can I create object with properties in javascript ?

Something like :

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

When I try to use this :

translate.city

It return undefined...

Upvotes: 0

Views: 65

Answers (1)

JLRishe
JLRishe

Reputation: 101662

You need to create an instance of your object:

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

Alternatively, you could do this:

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

If you want to be able to access the city property without calling it as a function and you are using ES5 or higher, you can define a getter method:

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

Or yet another way of defining a getter (also requires ES5):

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

And one more variation (provided by @vol7ron), which determines the city value when the object is created:

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

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

Upvotes: 2

Related Questions