Get And Set

Getters and Setters behave like properties when called, giving you an abstract way to organise your thoughts.

Unlike normal methods, using get and set lets you operate on the object's properties directly whilst doing hidden magic. So no need for a method.

They allow you to bind functions to an object that look like normal object properties ie. obj.age = 2, but actually execute hidden functions instead.

  • You can only have one getter or setter per name, on an object. (So you can have both one value getter and one value setter, but not two ‘value’ getters.)
  • The only way to delete a getter or setter is to do: ‘delete object[name];’ Be aware, that this command is capable of deleting normal properties, getters and setters. (So if all you want to do is remove a setter you need to backup the getter and restore it afterwards.)
  • If you use defineGetter or defineSetter it will silently overwrite any previous named getter or setter – or even property – of the same name.

Great guide: https://johnresig.com/blog/javascript-getters-and-setters/

Example 1

Without a getter and a setter. As you can see user.getFullName() looks unclean

var User = function User() {
  var firstname = 'John'; // private
  var lastname = 'Carroll'; // private
 
  this.getFullName = function getFullName() {
    return firstname + ' ' + lastname;
  }
  this.setName = function setName(f,l) {
    firstname = f;
    lastname = l;
  }
}
 
var user = new User();
console.log( user.firstname ); // undefined
console.log( user.getFullName() ); // John Carroll
user.setName('Mike','Carroll');
console.log( user.getFullName() ); // Mike Carroll

Converted to get/setter for private/protected variables

var Person = function(name) {
 
    this.name = name;
    var age = name.length;
 
    // private
    Object.defineProperty(this, 'age', {
      get  : function() {
        return age;
      },
      set  : function(newAge) { 
        age  = newAge;
      }
    });
}
 
var john = new Person('John');
console.log(john.name); // john
 
john.age = 50;
 
console.log(john.age); // 50

Converted for prototype

Now, if we wanted to, instead, define getters and setters within the context of our object prototype (and where having “private” data is less of a concern) we can then use an alternative object syntax for that.

var Person = function(name)  {
    this.name = name;
    this.age = 50;
}
 
Person.prototype = {
    get age(){
        return this._age; // notice underscore otherwise this.age will fire age() itself and you get a stack error
    },
    set age(val){ 
        this._age = val;
    }  
}; 
 
// Or
 
/* Person.prototype.age = {
    get() {
        return this._age;
    },
    set(val) { 
        this._age = val;
    }   
}; */
 
var john = new Person('John'); 
 
console.log(john.name); // john 
console.log(john.age); // 50
 
john.age = 10;
console.log(john.age); // 10

ES6 Method

// 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);
 
// Example 2 Es6 
class Ab{
    constructor(n){
        this.name = n;
    }
 
    get name(){ return this._name },
    set name(value){ this._name = value }
}

Object Literal way

var language = {
  set current(name) {
    this.log.push(name);
  },
  log: []
}
 
language.current = 'EN';
language.current = 'FA';
 
console.log(language.log);
// expected output: Array ["EN", "FA"]
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License