Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS getters and setters inside a class?

I'd like to create a class in JS that uses native getters and setters. I know I can create getters/setters for objects, like so:

var obj = {
    get value(){
        return this._value;
    },
    set value(val){
        this._value = val;
    }
}

I also know that I can use this.__defineGetter__ inside a class/function, but MDN says that using __defineGetter__() etc is discauraged.

Is there any better way to add getters and setters to js class than:

function class(){
};

class.prototype = {
   get value(){
        //....

}

?

like image 984
Kuba Orlik Avatar asked Feb 04 '14 22:02

Kuba Orlik


People also ask

Should I use getters inside class?

Yes, the methods of your class should call the getters and setters. The whole point in writing getters and setters is future proofing. You could make every property a field and directly expose the data to the users of the class.

What keywords create getters and setters in classes?

To add getters and setters in the class, use the get and set keywords.

What is get in JavaScript class?

The get syntax binds an object property to a function that will be called when that property is looked up.


2 Answers

2019: Hooray for ES6!

class Person {
    
    get name() {
        return this._name + '!!!'
    }

    set name(newValue) {
        this._name = newValue
    }

    constructor(name) {
        this._name = name
    }
}

const me = new Person('Zach')
console.log(me.name)            // Zach!!!

me.name = 'Jacob'
console.log(me.name)            // Jacob!!!

// Of course, _name is not actually private.
console.log(me._name)           // Jacob
like image 142
user1160006 Avatar answered Sep 19 '22 13:09

user1160006


The cleanest way to define properties on a class is via Object.defineProperties. This allows you to define all of your properties in a single, easily readable block. Here's an example:

var MyClass = function() {
    this._a = undefined;
    this._b = undefined;
};

Object.defineProperties(MyClass.prototype, {
    //Create a read-only property
    a : {
        get : function() {
            return this._a;
        }
    },
    //Create a simple read-write property
    b : {
        get : function() {
            return this._b;
        },
        set : function(value) {
            this._b = value;
        }
    }
});

There are a plethora of other options when defining properties, so be sure to check out the link I posted for more information. It's also important to keep in mind that even the most basic getter/setter property is only as fast as a method call in current browsers, so they can become a bottleneck in performance-intensive situation.

like image 41
Matthew Amato Avatar answered Sep 18 '22 13:09

Matthew Amato