javascript - Define getter / setter in object function -


i'm learning javascript, , wondering if possible define getters , setters in object functions. main difference way of calling it, if defined getfullname = function(), should call method myobj.getfullname(), however, arrays, getter allows called simple property myobj.fullname (without parenthesis).

as saw in mdn reference (http://mzl.la/1ciuuiw), done in object literals:

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

however, can't on object functions so:

function obj(name, lname){     this.name = name;     this.lastname = lname;      fullname(){          return this.name + " " + this.lastname;     } } 

getting "unexpected identifier" error...

as get xx(){} used var obj = {}; here use constructor create new object. should use mdn - object.defineproperty().

and if want fullname apply on object create obj, apply on prototype.

function obj(name, lname){    this.name = name;    this.lastname = lname;  }    object.defineproperty(obj.prototype, 'fullname', {    : function() {      return this.name + " " + this.lastname;    }  });    var aobj = new obj("first", 'lastn');  console.log(aobj.fullname);

update: if want more straight way, , not scared try new things, es2015's class notation can more easily:

// es2015 - class class obj {   constructor(name, lname) {     this.name = name;     this.lname = lname;   }    // define getter method fullname   fullname() {     return this.name + " " + this.lastname;   } }  var aobj = new obj('billy', 'hallow'); console.log(aobj.fullname); 

currently browsers don't support that, if want use in site, need use js compilers babel transpile es2015 es5.

babel provide playground has interest in es2015, can copy above codes playground see how works.


Comments