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?
On
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
The reserved word
selfis a pseudo variable (you cannot assign to it) that refers to the current receiver of the method where it is used. On the other sideyourselfis a message you can send to any object to get that very same object.The implementation of
yourselfismeaning that the message
yourselfwill behave as I just explained.The reason why
yourselfexists 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
msg2might answer with something different from thereceiveryou can append theyourselfmessage to ignore that answer and returnreceiverinstead. 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
receiveris not a variable but a complex expression, something like.Without using
yourselfyou 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,
selfis a reserved word that refers to the current receiver andyourselfis just a regular method that is there just for convenience.