0

I want to create an infinite depth 'anything' object that has the following two properties:

  1. Every property on the anything object is another anything object.
  2. Every property on the anything object is also a function that returns an anything object.

The purpose is for simple mocking of objects in tests when a more specific mock is not needed.

Property 1 is fulfilled by How do I make an object that has infinite depth through arbitrary properties in Javascript? but it is missing property 2. The solution must be in ES5 for runtime environment reasons.

var p = infiniteDepthObject();
// All of the following should be defined for arbitrary property names at any depth
p.foo
p.foo.bar
p.foo().bar
p.foo().bar()
p.foo.bar()
p.foo.bar.baz
p.foo.bar.baz()
p.foo.bar().baz
p.foo().bar.baz
p.someOtherPropertyChosenAtRunTime()
... etc

Can this be done in ES5 without a polyfill for Proxy?

EDIT: Not a duplicate of How does basic object/function chaining work in javascript?. I know I can return 'this' from a function to chain. The question is about defining all possible properties to be 'chain' methods. That is p.whateverYouCanImagine() returns p and also p.anyOldPropertyName as a property access returns p OR in both cases returns a new object that performs the same function as p. Not chaining, but some form of chaining may solve this problem. The difficult/different part is that at runtime I may choose a property to access that is not written into the object and it should still work.

koreus737
  • 661
  • 3
  • 9
  • 18
  • Not a duplicate. I know I can return 'this' from a function to chain. The question is about defining all possible properties to be 'chain' methods. That is p.whateverYouCanImagine() returns p and also p.anyOldPropertyName as a property access returns p OR in both cases returns a new object that performs the same function as p. – koreus737 Sep 13 '18 at 16:44
  • @ponury-kostek I have edited the question. Please unmark as duplicate, thanks. – koreus737 Sep 13 '18 at 16:52

1 Answers1

-1

This is a circular dependency:

const a = {};
a.a = a;

That's all, this is an infinite object, and you can replace the attribute a by a function to return same object

Jose Mato
  • 2,709
  • 1
  • 17
  • 18
  • That is not quite what I was asking. Can I do a.foo() or a.foo.bar()? Yes a.a.a.a.a is defined infinitely but I'm looking for an object that is defined for all properties. Any property name at all. – koreus737 Sep 13 '18 at 16:40
  • ah, understand, no, Proxy covers the functionality you want, because is in the middle of any call so internally can perform the necessary checks, but, without a proxy, is not possible at all – Jose Mato Sep 13 '18 at 17:19