In Smalltalk, there are two terms often found within a method body: self
and yourself
.
What is the difference between them?
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
returns anObject
.
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:
self aMessageReturningTheReceiver;
aMessageReturningTheArgument: anArgument .
^self
or
self aMessageReturningTheReceiver;
aMessageReturningTheArgument: anArgument;
yourself