在读取之前设置未定义的 javascript 属性

Set undefined javascript property before read

本文关键字:javascript 属性 未定义 设置 读取      更新时间:2023-10-31
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。其他或 tr['其他'] 以及对象的所有其他未定义属性以返回其名称而不是未定义?

三种解决方案:

  • 将您的对象实现为 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; }
    };
})();

您可以使用对象初始值设定项为属性定义 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

虽然这个解决方案不是你想要的,但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!']]]