开发者

How to chain make object with method call?

Let's say I have

WORLD: make object! [
      people: make Object! []
      cars: make Object! []
      factories: make Object! []
      creat开发者_如何学运维e: func[][print "new world"]
]

How can I chain with the create method? something like this doesn't work.

(make WORLD[])/create

This is the JavaScript I would like to emulate

(new WORLD()).create()


The idiom in this case is do get in:

>> do get in make object! [a: does [42]] 'a
== 42

IN returns the word 'a in the object's context. GET retrieves the value bound to 'a word (in that context). Finally as we expected the value returned by GET to be a function, we just call that function using DO.

For your example given, this would therefore look as follows:

do get in make WORLD [] 'create

As per Hostile Fork's suggestion in the comments, here is a fully parenthesised version of the last expression, to make function arity explicit:

do (get (in (make WORLD []) 'create))


Another approach is working a little more with REBOL's grain, that style of chaining really isn't to REBOL's strength:

WORLD: make object! [
      people: make Object! []
      cars: make Object! []
      factories: make Object! []
      create: does [print "new world"]
]

make WORLD [create]

Alternatively, if you're looking for a response from create (which you won't get in this instance as 'print returns unset!):

result: do bind [create] make WORLD []

It's perhaps a little clunky compared with chaining, but then chaining is old school language. Using 'bind is like having access to black magic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜