Is it possible to implement dynamic getters/setters in JavaScript?

前端 未结 4 1035
甜味超标
甜味超标 2020-11-22 17:39

I am aware of how to create getters and setters for properties whose names one already knows, by doing something like this:

// A trivial example:
function My         


        
4条回答
  •  忘掉有多难
    2020-11-22 17:51

    The following could be an original approach to this problem:

    var obj = {
      emptyValue: null,
      get: function(prop){
        if(typeof this[prop] == "undefined")
            return this.emptyValue;
        else
            return this[prop];
      },
      set: function(prop,value){
        this[prop] = value;
      }
    }
    

    In order to use it the properties should be passed as strings. So here is an example of how it works:

    //To set a property
    obj.set('myProperty','myValue');
    
    //To get a property
    var myVar = obj.get('myProperty');
    

    Edit: An improved, more object-oriented approach based on what I proposed is the following:

    function MyObject() {
        var emptyValue = null;
        var obj = {};
        this.get = function(prop){
            return (typeof obj[prop] == "undefined") ? emptyValue : obj[prop];
        };
        this.set = function(prop,value){
            obj[prop] = value;
        };
    }
    
    var newObj = new MyObject();
    newObj.set('myProperty','MyValue');
    alert(newObj.get('myProperty'));
    

    You can see it working here.

提交回复
热议问题