javascript - 在对象上定义 getter,以便所有未定义的属性查找返回 ""

标签 javascript node.js

基本上我需要能够做到这一点:

var obj = {"foo":"bar"},
    arr = [];
with( obj ){
   arr.push( foo );
   arr.push( notDefinedOnObj ); // fails with 'ReferenceError: notDefinedOnObj is not defined'
}
console.log(arr); // ["bar", ""] <- this is what it should be.

我正在寻找 {}.__defineGetter__ 的“全局”等价物或 {get}为了为所有未定义的属性 getter 返回一个空字符串(请注意,这与 undefined 的属性不同)。

最佳答案

您可以创建 Proxy每当访问未定义的属性时返回一个空字符串。

app.js:

var obj = {"foo":"bar"},
    arr = [],
    p = Proxy.create({
        get: function(proxy, name) {
            return obj[name] === undefined ? '' : obj[name];
        }
    });
arr.push( p.foo );
arr.push( p.notDefinedOnObj );

console.log(arr);

正如问题作者 David Murdoch 所指出的,如果您使用的是 node v0.6.18(撰写本文时的最新稳定版本),您必须在运行时传递 --harmony_proxies 选项脚本:

$ node --harmony_proxies app.js
[ 'bar', '' ]

请注意,如果您使用 with,此解决方案将不起作用,如下所示:

var obj = {"foo":"bar"},
    arr = [],
    p = Proxy.create({
        get: function(proxy, name) {
            return obj[name] === undefined ? '' : obj[name];
        }
    });
with ( p ) {
   arr.push( foo ); // ReferenceError: foo is not defined
   arr.push( notDefinedOnObj );
}

console.log(arr);

with 在将代理添加到作用域链时似乎没有调用代理的 get 方法。

注意:在本例中传递给 Proxy.create() 的代理处理程序是 incomplete。见 Proxy: Common mistakes and misunderstanding了解更多详情。

关于javascript - 在对象上定义 getter,以便所有未定义的属性查找返回 "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10727855/

相关文章:

javascript - 循环Json,搜索相同的键结尾,删除键结尾并将其放入新对象中

javascript - Bootstrap 模态未正确显示

javascript - jQuery 进度条仅在第一个加载

javascript - 在 iframe 脚本中使用 javascript 禁用超链接

node.js - NodeJs : globally installed module not found

node.js - 使用 django 和 nodejs 为 websocket 设置 nginx 的配置(wss ://)

node.js - pm2 --max-restarts 限制不工作和连续重启崩溃主机系统

用于深度优先搜索的 Javascript 扩展运算符

JavaScript 技巧。为什么 (a,b,c) => 5

node.js - 是否有使用带有 Node 的原始 Q promise 库异步递归遍历目录的示例?