我有一个像这样的对象:
const foo = {
bar: 'bar'
};
我想修改它,如果有人试图访问不存在的属性,则会抛出错误而不是返回undefined。
例如,
const baz = foo.baz;
// Error: Property 'baz' does not exist on object 'foo'
这可能吗?
答案 0 :(得分:2)
使用ECMAScript 6,您可以使用代理。
var original = {"foo": "bar"};
var proxy = new Proxy(original, {
get: function(target, name, receiver) {
console.log("Name of requested property: " + name);
var rv = target[name];
if (rv === undefined) {
console.log("There is no such thing as " + name + ".")
rv = "Whatever you like"
}
return rv;
}
});
console.log("original.foo = " + proxy.foo); // "bar"
console.log("proxy.foo = " + proxy.whatever); // "Whatever you like"