-2

In many OOP languages, to access a property of an object a get/set method is created.

Here's an example of what I mean in java

class MyClass{
    private int prop;
    public int getProp(){
        return this.prop;
    }
}

In JavaScript, is it better to access to object property in "OOP style" or just access directly?

class MyObj{
    constructor(a){
        this.a = a;
    }
    getA(){
        return a;
    }
}

o = new MyObj(1)
b = o.a //is this better?
b = o.getA() //or this?
Joseph Chotard
  • 666
  • 5
  • 15
Alex
  • 7
  • 6

2 Answers2

2

In Javascript class feature has been introduced with ES2015.

The feature is not fully supported by all browsers (IE does not support it, FF and Safari do not support private members plus other things).

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

In a more OO approach getter/setter are preferable when there is the need to perform a specific logic for specific properties, otherwise accessing public properties is just fine.

Reference: Are `getter` and `setter` necessary in JavaScript?

class MyPerson {
    constructor(name, age){
        this._name = name;
        this.age = age;
    }

    get name(){
        return this._name.charAt(0).toUpperCase() + this._name.slice(1);
    }
}

p = new MyPerson("mike", 25)
const personName = p.name;
const personAge = p.age;
  • 1
    the lack of private variables kind of makes them useless, unless you are using some kind of processing on the variable in the getter. Perhaps some day javascript will have them across all browsers. I was giddy when the finally gave us let. – John Lord Mar 22 '20 at 22:40
0

Javascript has no sense of public/private variables like Java has, or at least not yet (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields). Javascript is not really object-oriented. Classes have been added quite recently (ECMA Script 2015).

So I guess it's just a matter of choice. I believe the vast majority of javascript developers access properties directly without defining getters and setters.

hinosxz
  • 119
  • 5