Pulse7
9/8/2017 - 3:15 PM

Make property with getter setter

let person = {}; makeProp(person,"Name"); // person now have Name property person.Name="Nelson";

const makeProp = function(obj, propName) {
      let _prop = undefined;
      Object.defineProperty(obj, propName, {
        // Create a new getter for the property
        get: function() {
          console.log("get_"+propName);
          return _prop;
        },
        // Create a new setter for the property
        set: function(val) {
          console.log("set_"+propName);
          _prop=val;
        }
      })
    }