在Rebol 3中,您可以使用append:
动态地向对象添加键和值>> foo: object [x: 10]
>> append foo [y: 20 z: 30]
== make object! [
x: 10
y: 20
z: 30
]
但如果你尝试使用功能,它似乎不起作用:
>> foo: object [x: 10]
>> append foo reduce [y: does [print "y"] z: does [print "z"]]
** Script error: invalid argument: make function! [[][print "y"]]
** Where: append
** Near: append foo reduce [y: does [print "y"] z: does [print "z"]]
您可以使用extend添加函数:
>> foo: object [x: 10]
>> extend foo 'y does [print "y"]
>> foo/y
y
但这只允许你一次添加一个。如何向对象添加一个任意键/值块,其中一些是函数?
答案 0 :(得分:2)
由于延伸只是一个夹层,
>> source extend
extend: make function! [[
{Extend an object, map, or block type with word and value pair.}
obj [object! map! block! paren!] "object to extend (modified)"
word [any-word!]
val
][
if :val [append obj reduce [to-set-word word :val]]
:val
]]
您可以轻松定义自己的扩展或新功能
extends: make function! [ [{Extend an object}
obj [object!]
funcblk [block!] "with pair(s) of functionname and function"
] [
foreach [name funcon] funcblk [append obj reduce [to-set-word name get funcon]]
]]
然后你就可以了
>> r: does [print "y"] s: does [print "z"]
>> extends foo [y r z s]
== make object! [
x: 10
y: make function! [[][print "y"]]
z: make function! [[][print "z"]]
]
或简称
>> append foo reduce [quote y: does [print "y"] quote z: does [print "z"]]
== make object! [
x: 10
y: make function! [[][print "y"]]
z: make function! [[][print "z"]]
]