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

Intercept the fetching of properties / methods of a javascript object

本文关键字:属性 方法 对象 获取 javascript      更新时间:2023-09-26

我如何/可以拦截请求获取一个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都是"undefined"

在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

我不认为有一种方法来拦截访问未定义的属性。您总是可以执行以下操作

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.