2016-03-27 86 views
1

我有一個對象,如:投擲誤差不存在財產

const foo = { 
    bar: 'bar' 
}; 

我想修改它這樣,如果有人試圖訪問一個不存在的屬性的錯誤將是相當拋出比返回undefined。

例如,

const baz = foo.baz; 
// Error: Property 'baz' does not exist on object 'foo' 

這可能嗎?

回答

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" 

https://jsfiddle.net/u5b3wx9w/

+0

完美。這正是我所期待的!謝謝。 –