add a public property to a class in javascript

To add a public property to a class in Javascript, you need to first define the class, then add the property to the class definition as shown in the code block below:

index.tsx
// define the class
class MyClass {
   // constructor function
   constructor(name) {
      // private property
      this._name = name;
   }
   // public property
   get name() {
      return this._name;
   }
   set name(value) {
      this._name = value;
   }
}

// create an instance of the class
let myObject = new MyClass('Test');

// access the public property
console.log(myObject.name);   // output: Test

// change the value of the public property
myObject.name = 'New Value';

// access the updated public property
console.log(myObject.name);   // output: New Value
576 chars
28 lines

In the above code, the name property is defined as a getter/setter pair inside the class definition, which allows it to be accessed and modified publicly outside of the class. To access the property, simply create an instance of the class and call the property using the instance name.

gistlibby LogSnag