拦截获取javascript对象的属性/方法

时间:2013-03-01 12:47:13

标签: javascript

如何/我可以拦截获取javascript对象的方法/属性并返回自定义值的请求。

例如,

var obj = {
    // This "get" method is where I want to replace the call to get a property of an object.
    get : function(propertyName) {
        if (propertyName == 'somePropertyThatDoesntExist') { return 1; }
        else { return 0; } // Something like this?
};

// Either this method of access,
var myValue1 = obj.somePropertyThatDoesntExist
var myValue2 = obj.someOtherPropertyThatDoesntExist

// Alternatively, 
var myValue3 = obj['somePropertyThatDoesntExist']
var myValue4 = obj['someOtherPropertyThatDoesntExist']

因此myValue1和myValue3的值为1,myValue2和myValue4的值为0.

目前,myValue1,2,3,4都将被“未定义”。

2 个答案:

答案 0 :(得分:0)

我认为没有办法拦截对未定义属性的访问。您可以随时执行以下操作

if(obj.someProperty != undefined)
    obj.someProperty // access the property

或者,您可以编写get方法

var obj = {
    someProperty : "val",
    get : function(propertyName) {

        if (this[propertyName] == undefined) { return 0; }
        else { return this[propertyName]; } 
    }
};

并像

一样使用它
obj.get("someProperty") // returns 0 if property is not defined. 

答案 1 :(得分:0)

这可以在 JavaScript ES6 中使用 Proxy 对象

var obj = {}

// Wrap the object using Proxy
obj = new Proxy(obj, {
  get : function (target, propertyName) {
    if (propertyName === 'somePropertyThatDoesntExist') { return 1; }
    else { return 0; }
  }
})

var myValue1 = obj.somePropertyThatDoesntExist       // 1
var myValue2 = obj.someOtherPropertyThatDoesntExist  // 0