Set undefined javascript property before read

我是研究僧i 提交于 2019-11-26 10:03:38

问题


var tr={};
tr.SomeThing=\'SomeThingElse\';
console.log(tr.SomeThing); // SomeThingElse
console.log(tr.Other); // undefined

tr.get=function(what){
    if (tr.hasOwnProperty(what)) return tr[what];
    else return what;
};
tr.get(\'SomeThing\') // SomeThingElse
tr.get(\'Other\') // Other

Is there any way to make tr.Other or tr[\'Other\'] and all other undefined properties of the object to return its name instead undefined?


回答1:


You could define a getter for your property.




回答2:


Three solutions:

  • Implement your object as a Proxy, which is designed to do exactly what you want. Yet, it is only a draft and currently only supported in Firefox' Javascript 1.8.5 It was standardised with ES6, but might not yet be available in all environments.

  • Always fill your translation object with a complete set of messages. When creating that "dictionary" (serverside or clientside), always include all needed keys. If no translation exists, you can use a fallback language, the message's name or the string representation of undefined - your choice.

    But a non-existing property should always mean "there is no such message" instead of "no translation available".

  • Use a getter function with a string parameter instead of object properties. That function can look the messages up in an internal dictionary object, and handle misses programmatically.

    I would recommend a map object which is different from the dictionary, to allow "get" and co as message names:

var translate = (function(){
    var dict = {
        something: "somethingelse",
        ...
    };
    return {
        exists: function(name) { return name in dict; },
        get: function(name) { return this.exists(name) ? dict[name] : "undefined"; },
        set: function(name, msg) { dict[name] = msg; }
    };
})();



回答3:


While this solution isn't exactly what you were looking for, a JavaScript implementation of python's collections.defaultdict class might help:

var collections = require('pycollections');
var dd = new collections.DefaultDict([].constructor);
console.log(dd.get('missing'));  // []
dd.get(123).push('yay!');
console.log(dd.items()); // [['missing', []], [123, ['yay!']]]


来源:https://stackoverflow.com/questions/11503666/set-undefined-javascript-property-before-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!