Reputation: 47595
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
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
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