8
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

有没有办法让 tr.Other 或 tr['Other'] 以及对象的所有其他未定义属性返回其名称而不是未定义?

4

3 回答 3

5

三种解决方案:

  • 将您的对象实现为 a Proxy,它旨在完全按照您的意愿行事。然而,它只是一个草稿,目前仅在 Firefox 的 Javascript 1.8.5 中支持。它是用 ES6 标准化的,但可能尚未在所有环境中可用。

  • 始终用一整套消息填充您的翻译对象。创建该“字典”(服务器端或客户端)时,始终包含所有需要的键。如果不存在翻译,您可以使用备用语言、消息名称或undefined- 您选择的字符串表示形式。

    但是一个不存在的属性应该总是意味着“没有这样的消息”而不是“没有可用的翻译”。

  • 使用带有字符串参数而不是对象属性的 getter 函数。该函数可以在内部字典对象中查找消息,并以编程方式处理未命中。

    我会推荐一个不同于字典的地图对象,以允许“get”和 co 作为消息名称:

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; }
    };
})();
于 2012-07-17T13:34:56.227 回答
2

您可以使用对象初始值设定项为您的属性定义一个 getter :

var o = {
  a: 7,
  get b() {
    return this.a + 1;
  },
  set c(x) {
    this.a = x / 2;
  }
};

console.log(o.a); // 7
console.log(o.b); // 8 <-- At this point the get b() method is initiated.
o.c = 50;         //   <-- At this point the set c(x) method is initiated
console.log(o.a); // 25

或使用Object.defineProperties()

var o = { a: 0 };

Object.defineProperties(o, {
    'b': { get: function() { return this.a + 1; } },
    'c': { set: function(x) { this.a = x / 2; } }
});

o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.b); // Runs the getter, which yields a + 1 or 6
于 2012-07-16T11:52:10.247 回答
1

虽然此解决方案并不完全符合您的要求,但 python 的 collections.defaultdict 类的 JavaScript 实现可能会有所帮助:

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!']]]
于 2015-07-18T00:32:51.543 回答