In Smalltalk, there are two terms often found within a method body: self
and yourself
.
What is the difference between them?
In Smalltalk, there are two terms often found within a method body: self
and yourself
.
What is the difference between them?
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 sideyourself
is a message you can send to any object to get that very same object.The implementation of
yourself
ismeaning that the message
yourself
will behave as I just explained.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:If
msg2
might answer with something different from thereceiver
you can append theyourself
message to ignore that answer and returnreceiver
instead. Of course you could have achieved the same result by writing: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.Without using
yourself
you would have to add a temporary to save the value of the receiver to achieve the same:which is a little bit more verbose.
To summarize,
self
is a reserved word that refers to the current receiver andyourself
is just a regular method that is there just for convenience.self
is a synonym for an object: specifically the receiver of the message that invoked the method. It is used within the body of a method.yourself
is a message that you can send to an object, that returns the receiver of the message.anObject yourself
returnsanObject
.yourself
is often used at the end of a message cascade within a method body.When you want the return value from the method to be the receiver, but the final message in the cascade returns something else, you could write either:
or