What is the difference between self and yourself i

2019-03-18 05:16发布

问题:

In Smalltalk, there are two terms often found within a method body: self and yourself.

What is the difference between them?

回答1:

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.

The implementation of yourself is

yourself
    ^self

meaning 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:

^receiver
   msg1;
   msg2;
   yourself

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

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.

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

which is a little bit more verbose.

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.



回答2:

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