Jo Colina Jo Colina - 2 months ago 9
Javascript Question

Define getter / setter in object function

I'm learning JavaScript, and was wondering if it was possible to define getters and setters in object functions.
The main difference is the way of calling it, if defined as

getFullName = function()
, I should call the method as
myObj.getFullName()
, however, as for arrays, a getter allows for it to be called as a simple property
myObj.fullName
(without parenthesis).

As I saw in MDN reference (http://mzl.la/1CIUuIw), it is easily done in Object Literals:

var obj = {
get var(){
return "something";
}
}


However, I can't do it on object functions like so:

function obj(name, lname){
this.name = name;
this.lastName = lname;

get fullName(){
return this.name + " " + this.lastName;
}
}


Getting a "Unexpected identifier" error...

Answer

As get XX(){} is used for var obj = {}; But here you use a constructor to create new object. So you should use MDN - Object.defineProperty().

And if you want the fullName apply on all object create from obj, apply it on its prototype.

function obj(name, lname){
  this.name = name;
  this.lastName = lname;
}

Object.defineProperty(obj.prototype, 'fullName', {
  get : function() {
    return this.name + " " + this.lastName;
  }
});

var aObj = new obj("first", 'lastN');
console.log(aObj.fullName);

UPDATE: If you want a more straight way, and not scared to try new things, then ES2015's class notation can do it more easily:

// ES2015 - class
class obj {
  constructor(name, lname) {
    this.name = name;
    this.lname = lname;
  }

  // Define getter method for fullName
  get fullName() {
    return this.name + " " + this.lastName;
  }
}

var aObj = new obj('Billy', 'Hallow');
console.log(aObj.fullName);

Currently most browsers don't support that, if you want to use this in your site, you need to use js compilers like Babel to transpile it from ES2015 to ES5.

Babel also provide a playground for those who has interest in ES2015, you can copy above codes to the playground to see how it works.

Comments