Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is alternative before ES6 of getter method existing in ES6

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?

like image 959
Abdennour TOUMI Avatar asked Sep 13 '25 12:09

Abdennour TOUMI


1 Answers

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.

like image 194
Paul Avatar answered Sep 16 '25 03:09

Paul