Navigation:  Tutorials > Beginners Guide to Smalltalk > Objects and Messages > Cascading Messages >

Yourself

Previous pageReturn to chapter overviewNext page

Sometimes it is useful for a series of cascaded messages to answer, not the result of the last message, but the receiver of the messages itself. You can use the message, yourself, to do this. Compare the following two examples:

sequence := OrderedCollection new

       add: 1;

       add: 4;

       add: 9;

       add: 16.

 

Here, the displayed result is 16, which is answered by the final add: message (it is convention that any add: message will always answer its parameter). This is probably not what we want since the actual sequence of numbers has now been lost. More likely, the following is what is expected:

sequence := OrderedCollection new

       add: 1;

       add: 4;

       add: 9;

       add: 16;

       yourself.

 

The message yourself always answers the receiver that it is sent to. In this case the receiver is the OrderedCollection object and so, since yourself is the last message sent in the cascaded sequence, this is what is returned as the result.