0

When and why would we type object literals? Isn't it a bit primitive if the key value pairs can't interact? What am I missing, what's the educated way to go in the examples below?

Here gravity will result in NaN

var ball = {
    size:10,
    gravity:this.size/2
}

Here gravity will result in a successful 5

var ball = {
    size:10
}
ball.gravity = ball.size/2;

Here gravity will result in a successful 5

var ball = {};
ball.size = 10;
ball.gravity = ball.size/2;
Minzkraut
  • 2,149
  • 25
  • 31
Sinatra
  • 57
  • 4
  • 1
    Related (or dupe?): http://stackoverflow.com/q/4616202/1207195 – Adriano Repetti Sep 03 '15 at 06:17
  • It's like you said: If you have dependencies, then don't use object literals. But if you don't have dependencies, object literals save a lot of typing and are consequently less error-prone. – Raymond Chen Sep 03 '15 at 06:19
  • `this` is an implicit argument of functions, you have no functions there. You are basically doing `undefined/2===NaN`, where `this===undefined` in strict mode. – elclanrs Sep 03 '15 at 06:25

1 Answers1

0

Something like this

var ball = {
  g: 0,
  get gravity() {
    return this.g;
  },
  set gravity(n) {
    this.g = (parseFloat(n) || 0);
  },
  get size() {
    return (parseFloat(this.g) || 0) / 2;
  },
  set size(n) {
    this.g = (parseFloat(n) || 0) * 2.0;
  }
}

ball.gravity = 10;
console.log(ball.size)
// 5
ball.size = 4;
console.log(ball.gravity)
// 8
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87