You cannot. bar is called before the object is constructed, obj will be undefined and the already-evaluated values of the previous properties (1 and 2) are somewhere inaccessible in memory only. See also Self-references in object literals / initializersSelf-references in object literals / initializers.
Given you found this question in a quiz with pretty arbitrary restrictions, they seem to expect a trick answer. There are several ways:
Access to source code and evaluate the object literal yourself
Simply return a constant, given that
obj.xandobj.yare constant in the given code as wellOverwriteconsole.logto do your bidding, for examplefunction bar() { var log = console.log.bind(console); console.log = function(p) { log(p.valueOf()); }; return { valueOf: function() { return obj.x + obj.y; } }; }Doesn't work unfortunately due to
console.logbeing dereferenced beforefoo()is called.
A similar approach does work in environments where theconsole.logbehaviour can be customized without needing to overwrite anything:function bar() { return { inspect: function() { return String(obj.x + obj.y); } }; }Just call
foo()yourself to get the values, but don't recurse infinitely onbar:function bar() { if (foo.stop) return null; foo.stop = true; var res = foo().x + foo().y; foo.stop = false; return res; }