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?
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.