Search code examples
javascriptfunctionclassget

javascript: classes and get methods before class syntax


i am creating a class in a old way without the new class syntax like this:

function User(name, lastname){
  this.name = name;
  this.lastname = lastname;
  this.fullname = function(){
    return this.name+' '+this.lastname;
  }
}

i would like to use fullname as a get method. but i don't get how to do it.

for example i would like to call it this way:

var u = new User('dario', 'developer');
console.log(u.fullname);

basically without parentheses. I know with the new class syntax you can use the get keyword. but how can i do it with this way of creating classes?


Solution

  • You should use Object.defineProperty (BEWARE: it's supported from ES5 onward, otherwise you have to make it thorugh an object literal declaration, but that would need to change your current code a bit more) if you want to keep your current scenario.

    function User(name, lastname){
      this.name = name;
      this.lastname = lastname;
      Object.defineProperty(this, "fullname", {
        get: function() {
          return this.name+' '+this.lastname;
        }
      });
    }
    
    var u = new User('dario', 'developer');
    console.log(u.fullname);