0

I apologize that I don't know of a better way of titling my question--suggestions appreciated. I know that this is valid:

var cyclic = new Object();
cyclic.c = cyclic;

and that this doesn't break

var cyclic = {c: this};

So I was wondering--why doesn't this work?

var foo = {a: 10, b: 5, c:(this.a - this.b)};

Is it because the elements reference other elements at the same 'level', or that I'm trying to do it all in one step? Is there a way to do this sort of thing in one line?

bibliolytic
  • 125
  • 6

2 Answers2

0

this isn't the literal object it's the window object because you're not calling it with a function.

You could/should utilise a constructor function for this instead,

consider the function below

var Foo = function(a, b) {
    this.a = a; //if you want to save state inside the object
    this.b = b; //else skip it.
    this.c = a - b;
}

//create a new object from Foo

var foo = new Foo(10, 5);
foo.c
>> 5 
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • If you have a constructor function (that is called with `new`), do not `return` an object literal!!! – Bergi Jan 10 '14 at 16:13
0

this doesn't point to what you think it does. When inside a function, this will point to the object that function was called on:

var o = { foo : function(){ console.log(this); } };
o.foo() // will log o

var o2 = { {bar : {foo : function(){ console.log(this); } } };
o2.bar.foo() // will log o2.bar

If the function is not called on any object or if this is not inside a function, then it will point to the global object, window.

var foo = function() { console.log(this); };
foo(); // will log window
console.log(this) // will log window

When you do:

var cyclic = {c: this};

You have created an object named cyclic which has a property c which references the global object.

Similarly, when you do:

var foo = {a: 10, b: 5, c:(this.a - this.b)};

You create an object with a property which references the a and b properties of the global object.

One thing you could do is create an init function:

var foo = { a:10, b:5, init : function(){ this.c = this.a - this.b } };

To have this be foo, you simply need to call the function as foo.init().

foo.init(); // adds the c property to foo, with the value foo.a-foo.b
console.log(foo.c);
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • I'm glad i could help you, but you should look at the other linked questions which are very similar to yours to find some other ways of dealing with your issue. – Tibos Jan 10 '14 at 16:35