简体   繁体   English

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

[英]Intercept the fetching of properties / methods of a javascript object

How/Can I intercept a request to get a method/property on an javascript object and return a custom value instead.我如何/如何拦截在 javascript 对象上获取方法/属性的请求并返回自定义值。

For example,例如,

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']

So myValue1 and myValue3 will have a value of 1, and myValue2 and myValue4 will have a value of 0.因此 myValue1 和 myValue3 的值为 1,myValue2 和 myValue4 的值为 0。

Currently, myValue1, 2, 3, 4 would all be "undefined".目前, myValue1, 2, 3, 4 都是“未定义的”。

I don't think there is a way to intercept access to a property that is undefined.我认为没有办法拦截对未定义属性的访问。 You can always do the following您始终可以执行以下操作

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

alternatively, you can write a get method或者,您可以编写一个 get 方法

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

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

and use it like并像使用它一样

obj.get("someProperty") // returns 0 if property is not defined. 

This is possible in JavaScript ES6 using the Proxy object这在 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM