Phillip Senn
Phillip Senn

Reputation: 47595

Defining getters and setters after the object is instantiated

This bit of code comes from MDN:

var o = {
  a: 7,
  get b() { 
    return this.a + 1;
  },
  set c(x) {
    this.a = x / 2
  }
};
$('body').append(o.a + '<br>')
$('body').append(o.b + '<br>')
o.c = 50;
$('body').append(o.a + '<br>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

What I would like to do is break it down even further. I've gotten as far as line 3 like so:

var o = {}
o.a = 7
o.get b() { // broken

Is there a way that I can break the getters and setters out so that it's not one long definition inside the o = {}?

Upvotes: 2

Views: 85

Answers (2)

Nick Messing
Nick Messing

Reputation: 504

Object.defineProperty is what you're looking for:

var o = {};
Object.defineProperty(o, 'a', {
  get: function() { return 1; },
  set: function(val) { console.log(val) }
});

Upvotes: 3

Michał Perłakowski
Michał Perłakowski

Reputation: 92461

You can achieve this using Object.defineProperty():

Object.defineProperty(o, "b", {
  get: function() {
    // return something
  }
})

See demo below:

var o = {};
o.a = 1;
Object.defineProperty(o, "b", {
  get: function() {
    return this.a + 1;
  }
});
console.log(o.b)

Upvotes: 1

Related Questions