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);