Frage

I'd like to set a property to an object using prototype, if it's possible, so that when I try to get an undefined value, it returns a default instead of undefined, like:

obj = {
  lang : {en: 'hello', it:'ciao'}
}

Example 1: obj.lang.es (undefined) - I'd like to get obj.lang.en instead of undefined.

Example 2: obj.something.else - I'd like to get false instead of an error because it can't read else of undefined.

War es hilfreich?

Lösung

It is probably not a good idea. Better use a root or default key:

obj = {
    lang : {root: 'hello', en: 'hello', it:'ciao'}
}

So you can ask for a lang in this way:

var hi = obj.lang.es || obj.lang.root;

You can use this in combination with a getter method:

var getTranslation = function(lang) {
    return obj.lang[lang] || obj.lang.root;
};
var hi = getTranslation("es");

Andere Tipps

This is not a pretty solution, but here it goes, create a prototype object that for any language defers the result to a default language. Then your particular object inherits from that prototype object and overrides any value it wants.

var languages = ['en', 'it', 'es']; // fill with every language you will ever use
var defaultLang = 'en';

var protoLang = Object.create(null);
function getDefaultLanguage(){
  return this[defaultLang];
}
languages.forEach(function(language){
  Object.defineProperty(protoLang, language, {
    get : getDefaultLanguage
  });
});


var obj = {
  lang : Object.create(protoLang, {
    en : { value : 'hello' },
    it : { value : 'ciao' }
  })
};


obj.lang.es // "hello"
obj.lang.en // "hello"
obj.lang.it // "ciao"

The thing is that you have to define every property first, that is why you need the languages array.

I agree with @DCoder. Maybe something like this:

function getLang(lang) {
    var result = this.obj[lang];
    if ( typeof result == 'undefined' ) {
        result = this.obj.en;
    }
    return result;
}

You do not need ; inside object, there no content in obj.lang, instead try it like this:

obj = {
  lang: {en: 'hello', it: 'ciao'}
};

if (obj.lang.hasOwnProperty("en")) {
  console.log(obj.lang.en);
} else {
  console.log(false);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top