What is the difference between self and yourself in Smalltalk?

前端 未结 2 1478
轻奢々
轻奢々 2021-02-05 06:36

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

What is the difference between them?

2条回答
  •  死守一世寂寞
    2021-02-05 07:05

    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
    

提交回复
热议问题