1

In ColdFusion (a server-side language), it's possible to have CF generate any getters and setters in a class for you, like so:

component output="false" accessors="true" {

    property string title;

    public any function init() output = false {

        setTitle("");
        return this;

    }

}

Here, I never write the setTitle() setter, it's just implicit.

Is there any such thing for JavaScript (or even jQuery) in either ES5 / ES6 / ES7?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Michael Giovanni Pumo
  • 14,338
  • 18
  • 91
  • 140

1 Answers1

3

You can assign arbitrary properties to any object without explicitly writing setters/getters.

Although you can use them if you like.

function myClass() {}

Object.defineProperty(myClass.prototype, "bar", {
  get: function get_bar() {
    return this._bar;
  },
  set: function set_bar(value) {
    this._bar = value;
    alert(value);
  }
});

var instance = new myClass();
instance.foo = "123"; // Arbitary
instance.bar = "456"; // Explicit setter/getter
console.log(instance.foo, instance.bar);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Just to note since this is tagged with ES6, there is an inline syntax for these now, ```class myClass { get bar(){ return this._bar; } set bar(value){ this._bar = value;} }``` – loganfsmyth May 26 '15 at 23:29