Search code examples
javascriptfunctiongetter-setter

Is there a way to use property get and set notation in a JS function class?


Is there a way in JavaScript's constructor functions to use getter and setter syntax for properties?

Here is an example of my desired syntax:

function DemoClass()
{
	var mFooProperty = 0;
  
	get FooProperty()
	{
		return mFooProperty;
	}

	set FooProperty(value)
	{
		mFooProperty = value;
	}
}

var anInstance = new DemoClass();
console.log(anInstance.FooProperty);
anInstance.FooProperty = 42;
console.log(anInstance.FooProperty);


Solution

  • In order to keep the real storage for that property as a private variable, you'd have to use an Object API to define the getter and setter in the constructor:

    function DemoClass() {
      var mFooProperty = 0;
      Object.defineProperties(this, {
        fooProperty: {
          get: function() { return mFooProperty; },
          set: function(value) { mFooProperty = value; }
        }
      });
    }
    

    Now when you construct an instance, the instance will appear to have a property called "fooProperty". Referencing the value of the property will invoke the "getter" function, and setting the value calls the "setter":

    var d = new DemoClass();
    console.log(d.fooProperty); // calls getter 0
    d.fooProperty = 3;          // calls setter
    console.log(d.fooProperty); // 3