Home / Blog / Using Getters and Setters in JavaScript

Blog Using Getters and Setters in JavaScript

Using Getters and Setters in JavaScript

Using Getters and Setters in JavaScript

Creating Objects in Javascript allows complex functionality while exposing only certain functions. Sometimes it's helpful to expose Object properties as well and unless they're simply read-write attributes, it may not be immediately clear how to how to do it.

Simple JavaScript Objects

As we covered in a previous post, simple Objects in JavaScript can be defined in a couple ways:

// Simple function-as-an-Object
function Person() {
    this.name = "Jimmy";
};
let person = new Person();

// When using objects as 'containers', this is much simpler
let person = { name: "Bill" };

Simple JavaScript Objects

Creating a read-only property on each of these is slightly different, but neither one is difficult if you know how. If the property isn't something that should be changed or replaced, we can add a read-only property by adding a getter method as follows:

var person = {
    phoneNumbers: {cell: '555-1234', work: '555-7890', home: '555-9990'},
    get phones(){
        return Object.keys(this.phoneNumbers);
    }
}
console.log(person.phones);
// prints: ["cell", "work", "home"]

If you've used the function-as-an-Object means means of creating your Object, you need to manipulate the new Object's prototype as follows:

// Simple function-as-an-Object
function Person() {
    this.name = "Jimmy";
    this.phoneNumbers = {home: '555-6547', emergency: '555-8520'};
};
Object.defineProperties(Person.prototype, {
    phones : {
        get : function() {
            return Object.keys(this.phoneNumbers);
        }
    }
});
let person = new Person();
console.log(person.phones);
prints: ["home", "emergency"]

Both examples provided here work the same way for creating custom setters as well, if your situation demands it. Keep in mind that a regular property may be more performant but it's not always an option. As always, if you're writing JavaScript for the web, check out the browser compatibility, and other details at mozilla.org.

Mark Voorberg

Co-Founder

Mark has been doing database design and building custom software for over twenty years. With a background in electronics, he quickly moved into software development and has been building database software solutions ever since, on many projects of all sizes.