1

I have a set of nested objects, and need to get a slot from the containing object. Can it be done?

Example:

Foo := Object clone do(
    a := "hello"

    Bar := Object clone do(
        b := Foo a  # How to get `Foo a` here?
    )
)

From the above code, I get an exception in the nested object Bar when accessing Foo:

Exception: Object does not respond to 'Foo'

The reason I would like to have these as nested objects, is because it would make it easier (IMO) to make the application more modular. If it was possible I could easily do something like

Foo := Object clone do(
    someSlot := "Some value"

    Bar := doRelativeFile("./folder/bar.io")
)

and in folder/bar.io use Foo someSlot if needed.

Think of e.g. someSlot as a database connection, and Bar as a data-model needing that database connection.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    `Foo` hasn't been assigned yet when you evaluate it. Maybe create a getter? Reminds me of the [Self-references in object literal declarations](http://stackoverflow.com/q/4616202/1048572) in JavaScript - with similar solutions. – Bergi Aug 12 '14 at 12:53

1 Answers1

0

I solved by creating an intialize method in the nested object, which takes the containing object as a parameter and returns self (i.e. the nested object.

So I can have two files like this:

  1. a.io

    Foo := Object clone do(
        foo := "foobar"
    
        Bar := doRelativeFile("./b.io") initialize(thisContext)
    )
    
  2. b.io

    Bar := Object clone do(
        initialize := method(parent,
            writeln("parent foo is ", parent foo)
            return self
        )
    )
    

While not a perfect solution, it should work well enough for my purposes.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621