在 Smalltalk 中,您向接收者发送消息。
例如
Animal new 将 new 消息发送到 Class Animal。
这是一个一元消息的例子。
Transcript show: a 将 show: 消息发送到 Class Transcript,参数为 a。
这是关键字消息的示例。
Transcript cr 将消息 cr 发送到 Class Transcript。
这是一元消息的另一个例子。
Transcript show: a ;
cr .
这是消息级联的示例,其中一行中的多条消息被发送到同一个接收者。
在消息级联中,您只需键入一次接收者的名称,使用; 分隔每条消息的其余部分。
Transcript show: a ;
cr .
在 Smalltalk 中,有参数的关键字必须有一个冒号后缀。
约定是简单访问器使用与它们访问的实例变量相同的名称; Class Object 的实例将具有 anObject 形式的变量名。
所以一个名为name 的实例变量将有一个名为name 的getter 和一个名为name: 的setter
按照惯例,我们会有:
anAnimal := Animal new.
Transcript show: anAnimal name ;
cr .
在这里,我们将name 消息发送到anAnimal。它返回 anAnimal 的名称。作为一元消息,它的优先级高于关键字消息Transcript show: <something>,因此首先被评估。 anAnimal name 消息的返回值成为Transcript show: <something> 消息的参数。
你可以自己看看。在工作区中,突出显示anAnimal name,然后单击并选择“检查它”。这将打开一个 Inspector 窗口,它会显示anAnimal name 消息返回的对象。
这些答案或许能帮助你理解:
Explain a piece of Smalltalk code
Keyword messages in smalltalk
本文Beginning to Smalltalk: Hello World 使用Transcript show: 'Hello World' 对其进行了更详细的介绍。