0

I am trying to understand how OOP stuff work in JavaScript. Coming from a java background I am used to creating classes as follows,

public class Person {
   private String name;

   public Person(String name) {
       this.name = name;
   }

   public String getName() {
        return this.name;
   }

   public void getName(String name) {
        this.name = name;
   }
}

Now I am writing the same class in JavaScript in the following way

class Person {

     constructor(name) {
         this.name = name;
     }

     get getName() {
         return this.name;
     }

     set setName(name) {
         this.name = name;
     }
 }

Now what I am expecting is that the variable "name" in the class to be only accessed via the setter and getter functions. However when I am able to change change the value of the name just simply by using the dot notation. Is there way of making the variable only to be accessed by the functions?

aspire29
  • 461
  • 3
  • 16
  • JavaScript doesn't have classical OOP. The `class` syntax is just a syntactic sugar with a misleading name. JavaScript uses prototypical inheritance (where objects inherit from objects, as opposed to objects being instances of classes which inherit from classes). – 4castle Dec 26 '17 at 17:36
  • You can use typescript because typescript is related to OOP concept like Class, Inheritance etc.... – kusama Jan 02 '18 at 07:19
  • class Person { private name:string; constructor(name:string) { this.name = name; } public get getName():string { return this.name; } public set setName(name:string) { this.name = name; } } – kusama Jan 02 '18 at 07:28

0 Answers0