最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is alternative before ES6 of getter method existing in ES6 - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Nov 11, 2016 at 4:11 Abdennour TOUMI asked Aug 15, 2016 at 18:00 Abdennour TOUMIAbdennour TOUMI 93.8k42 gold badges268 silver badges269 bronze badges 2
  • 1 Not a method, and not called as ATTRIBUTE, but rather, "referred to as property". – user663031 Commented Aug 15, 2016 at 18:44
  • @torazaburo: You removed too much whitespace ;) – Felix Kling Commented Aug 15, 2016 at 18:52
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

发布评论

评论列表(0)

  1. 暂无评论