问题描述
在Smalltalk中,方法主体中经常有两个术语:self
和yourself
.
In Smalltalk, there are two terms often found within a method body: self
and yourself
.
它们之间有什么区别?
推荐答案
保留字self
是一个伪变量(您不能分配给它),它引用使用该方法的当前接收者.另一方面,yourself
是一条消息,您可以将其发送到任何对象以获得该对象.
The reserved word self
is a pseudo variable (you cannot assign to it) that refers to the current receiver of the method where it is used. On the other side yourself
is a message you can send to any object to get that very same object.
yourself
的实现是
yourself
^self
表示消息yourself
将按照我刚才的解释行事.
meaning that the message yourself
will behave as I just explained.
yourself
存在的原因是为了支持消息级联,您将其作为最后一条消息放置在该消息中,以确保结果表达式将与接收方一起回答:
The reason why yourself
exists is to support message cascading, where you put it as the last message to make sure the resulting expression will answer with the receiver:
^receiver
msg1;
msg2;
yourself
如果msg2
可能回答的内容与receiver
不同,则可以附加yourself
消息以忽略该答案,而返回receiver
.当然,您可以通过编写以下内容来达到相同的结果:
If msg2
might answer with something different from the receiver
you can append the yourself
message to ignore that answer and return receiver
instead. Of course you could have achieved the same result by writing:
receiver
msg1;
msg2.
^receiver
由于这两个示例都很简单,因此可能很难理解其优势.但是,请考虑receiver
不是变量,而是复杂的表达式,例如.
Because of the simplicity of these two examples, it might be hard to understand what the advantage would be. However, consider that receiver
is not a variable but a complex expression, something like.
^(self msg: arg1 arg: arg2)
msg1;
msg2;
yourself.
在不使用yourself
的情况下,您必须添加一个临时文件来保存接收器的值以实现相同的目的:
Without using yourself
you would have to add a temporary to save the value of the receiver to achieve the same:
| answer |
answer := self msg: arg1 arg: arg2.
answer
msg1;
msg2.
^answer
有点冗长.
总而言之,self
是一个保留字,它指向当前的接收者,而yourself
只是为了方便起见而使用的常规方法.
To summarize, self
is a reserved word that refers to the current receiver and yourself
is just a regular method that is there just for convenience.
这篇关于Smalltalk中的自我和自己之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!