4

Getter method in ES6 is defined as METHOD & called as ATTRIBUTE (calling obj.method instead of obj.method(..))

Example :

class Job  {
    constructor(){
        this.start=new Date();
    }

    get age(){
        return new Date()-this.start;
    }
}

then:

var vm=new Job();
//....
vm.age // call Getter method  

My question is: What is the alternative to that before ES6, if any?

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254

2 Answers2

8

Since ES5 you have been able to define getters and setters using Object.defineProperty. Your ES6 code is essentially syntactic sugar for the following ES5 code:

function Job ( ) {
    this.start = new Date;
}

Object.defineProperty( Job.prototype, 'age', {
  get: function ( ) { return new Date - this.start; }
} );

Before that some engines had non-standard support for getters, such as Object.prototype.__defineGetter__, which would've be used like this to replicate your functionality:

Job.prototype.__defineGetter__( 'age', function ( ) {
  return new Date - this.start;
} );

SpiderMonkey also had some other ways to do it even earlier:

Job.prototype.age getter = function() {
    return new Date - this.start;
};

// or, this one, which declares age as a variable in the local scope that acts like a getter

getter function age() { ... };

None of those ways should be used today, except for Object.defineProperty which is still very useful in ES6.

Paul
  • 139,544
  • 27
  • 275
  • 264
3

Since ES5 each property of an object has a Getter and Setter functions. You can find the full documentation here: MDN - Object.defineProperty()

When you create an object you can then define a new property and tell which functions to use when getting and setting that value:

var obj = {};

Object.defineProperty( obj, 'propName', {
  get: function() { return 42; },
  set: function(newValue){ this.propName = newValue; }
});

In your ES6 code what you're doing is defining a new constructor function and then defining the getter for the age.

MarcoL
  • 9,829
  • 3
  • 37
  • 50