1

有人说您可以使用 get 与 Rebol 进行(实现继承)。所以我尝试了:

shape: context [
  x: 0
  y: 0
  draw: func['object][
    probe get object
  ]
]

circle: make shape [
  radius: 10
  draw: get in shape 'draw
]

rectangle: make shape [
  draw: get in shape 'draw
]

我想通过引用而不是值传递对象,所以我只使用'Object. 但是我必须这样称呼它

circle/draw 'circle

这是相当蹩脚的,因为我需要重复两次名称 circle 而在通常的继承中,有 this 关键字可以避免这种不自然的语法。有没有更优雅的方式?

谢谢。

4

3 回答 3

2

self一句话。冒着对此产生错误的确定感的风险,我会给你一个例子,它可能会做你想做的事:

shape: make object! [
    x: 0
    y: 0
    draw: func [object [object!]] [
        probe object
    ]
]

circle: make shape [
    radius: 10
    draw: func [] [
        shape/draw self
    ]
] 

rectangle: make shape [
    draw: func [] [
        shape/draw self
    ]
]

在这里,我们通过使用适当的“self”调用基类函数来制作接受零参数的函数

当心:就像换句话说,它被绑定了......并且绑定棒。一旦你开始使用抽象,这可能会变得很棘手......

selfWordAlias: func [] [
    return 'self
]

triangle: make shape [
    draw: func [] [
        shape/draw get selfWordAlias
    ]
]

打电话triangle/draw可能会让你大吃一惊。您在对象方法中,selfWordAlias 返回单词“self”。但是self的概念在定义 selfWordAlias 时被捕获和绑定,这是在全局系统上下文中。所以这就是你得到的。

有一些工具可以解决这个问题,但请确保您牢牢掌握Rebol 中的范围界定

于 2010-01-05T00:11:58.903 回答
1

我会认为使用 Rebol 的原型继承就是你所需要的。它更简单,更优雅:

shape: make object!
  x: 0           
  y: 0
  draw: func [] [probe self]
]

circle: make shape [
  radius: 10
]

triangle: make shape []

这给出了以下结果:

>> shape/draw
make object! [
    x: 0
    y: 0
    draw: func [][probe self]
]
>> circle/draw            
make object! [
    x: 0
    y: 0
    draw: func [][probe self]
    radius: 10
]
>> triangle/draw          
make object! [
    x: 0
    y: 0
    draw: func [][probe self]
]
于 2010-01-15T08:22:38.163 回答
1

当我想对所有对象使用相同的函数(而不是函数的副本)时,我会使用此方法。每当您创建一个对象时指向该函数,即使您复制另一个对象也是如此。

>> f: does [print "hello"]
>> o: context [a: 1 b: :f]
>> o/b
hello
>> p: context [a: 2 b: :f]
>> p/b
hello

>> same? get in o 'b get in p 'b
== true ;they are exactly the same function

>> append last second :f " world!" ;change the function
== "hello world!"
>> o/b
hello world!
>> p/b
hello world!

当然,您应该注意绑定问题。希望这会有所帮助。

于 2010-07-27T07:55:17.000 回答