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

Dav*_*och 9 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.
Run Code Online (Sandbox Code Playgroud)

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

thi*_*eek 9

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);
Run Code Online (Sandbox Code Playgroud)

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

$ node --harmony_proxies app.js
[ 'bar', '' ]
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用此解决方案将无法使用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);
Run Code Online (Sandbox Code Playgroud)

withget在将代理添加到作用域链时,似乎没有调用代理的方法.

注意:传递给Proxy.create()此代理处理程序的示例是不完整的.请参阅代理:常见错误和误解以获取更多详细信息.