Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 400
Katie Epps Avatar asked Sep 12 '25 12:09

Katie Epps


2 Answers

You can make use of a class in Javascript and set the properties as a class instance and then use getters/setters like

class DemoClass {

    constructor() {
       this.mFooProperty = 0;
    }
  
	get FooProperty() {
		return this.mFooProperty;
	}

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

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

According to documentation:

The bodies of class declarations and class expressions are executed in strict mode i.e. constructor, static and prototype methods, getter and setter functions are executed in strict mode.

like image 124
Shubham Khatri Avatar answered Sep 15 '25 01:09

Shubham Khatri


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
like image 36
Pointy Avatar answered Sep 15 '25 02:09

Pointy