在对象上定义getter,以便所有未定义的属性查找返回“"” [英] Define getter on object so all undefined property lookups return ""
问题描述
基本上我需要能够这样做:
Basically I need to be able to do this:
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返回一个空字符串(请注意,这与<$的属性不同) c $ c> undefined )。
I'm looking for a "global" equivalent of {}.__defineGetter__
or {get} in order to return an empty string for all undefined property getters (note that this is different than a property that is undefined
).
推荐答案
您可以创建 代理
每当未定义的属性返回空字符串访问。
You can create a Proxy
to return an empty string whenever undefined properties are accessed.
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指出的那样,如果您使用的是节点v0.6.18(最新的稳定版本发布于写这篇文章的时间),你必须在运行脚本时传递 - harmony_proxies
选项:
As question author David Murdoch notes, if you are using node v0.6.18 (the latest stable release at the time this post was written), you must pass the --harmony_proxies
option when you run the script:
$ node --harmony_proxies app.js
[ 'bar', '' ]
请注意,如果您将与
一起使用,此解决方案将不,如:
Note that this solution will not work if you use with
, as in:
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
does not seem to call the proxy's get
method when adding the proxy to the scope chain.
注意:代理处理程序传递给 Proxy.create()
在这个示例中不完整。有关更多详细信息,请参阅代理:常见错误和误解。
Note: the proxy handler passed to Proxy.create()
in this is example is incomplete. See Proxy: Common mistakes and misunderstanding for more details.
这篇关于在对象上定义getter,以便所有未定义的属性查找返回“"”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!