How can I define a default getter and setter using ECMAScript 5?

前端 未结 6 828
忘了有多久
忘了有多久 2020-12-07 01:14

How can I specify a default getter for a prototype? With default getter I mean a function that is called if obj.undefinedProperty123 is called.

I tried

6条回答
  •  悲哀的现实
    2020-12-07 01:37

    In ECMAScript 5, you can only intercept get/set operations on specific named properties (not universally all properties) via Object.defineProperty:

    Object.defineProperty(someObj, "someProp", {
        get: function() {
            console.log("you tried to get someObj.someProp");
            return "foo";
        }
    });
    

    Here, the get function will run any time code tries to read someObj.someProp.

    In the upcoming ECMAScript 6 draft, this will be possible via proxies. A proxy has an underlying target object and set/get functions. Any time a set or get operation happens on any of a proxy's properties, the appropriate function runs, taking as arguments the proxy's target object, property name used, and the value used in a set attempt.

    var proxyHandler = {
        get: function(obj, name){
            console.log("you're getting property " + name);
            return target[name];
        },
        set: function(obj, name, value) {
            console.log("you're setting property " + name);
            target[name] = value;
        }
    }
    
    var underlyingObj = {};
    
    // use prox instead of underlyingObj to use get/set interceptor functions
    var prox = new Proxy(underlyingObj, proxyHandler);
    

    Here, setting to getting property values on prox will cause the set/get functions to run.

提交回复
热议问题