Smalltalk в примерах/Сообщения: различия между версиями
Содержимое удалено Содержимое добавлено
Строка 169:
==Получатель сообщения==
Все сообщения должны посылаться объектам
MyClass>>doThis
array := Array new: 3.
array at: 1 put: 2.
(Обычно используемое обозначение указания имени метода стороны экземпляра: <tt>
<!--
===сам===▼
The receiver of the message
All messages have to be sent to an object — there's no such thing as a message in isolation. If you create an object in a method, it's easy to send a message to the object. For example:
MyClass>>doThis
array := Array new: 3.
array at: 1 put: 2.
(The generally used notation to show instance side method names is ClassName>>methodName. For classside methods, the notation isClassName class>>methodName.)
-->
Средняя длинна метода в Smalltalk 7 строк, поэтому, для того чтобы объект сделал серьёзную работу, хорошей практикой является разделение работы между несколькими методами (надеюсь, ты хочешь иметь короткие методы). Как вызвать другой метод, определённый в том же объекте? Ответ: объект посылает сообщение самому себе. В Smalltalk есть для этого специальная переменная --- <i>сам</i> --- которая всегда ссылается на объект который вызвал код --- получатель сообщения. Заметьте что <i>сам</i> ссылается на получателя даже когда код был определён в суперклассе класса получателя.
Строка 186 ⟶ 197 :
Если метод нуждается в другом методе для выполнения некоторой работы, пошлите сообщения <i>сам</i>. Фактически, если вы не знаете какому объекту послать сообщение, хорошим правилом будет послать его <i>сам</i>.
<!--
Smalltalk methods average about seven lines, so for an object to do any serious work there's a good chance
that you will have split the work into several methods (assuming you want to have short methods). How does a
method invoke another method defined on the same object? Answer: the object sends a message to itself.
Smalltalk has a special variable for just such use — self — which always refers to the object that is executing the
code — the message receiver. Note that self refers to the receiver even if the the code was defined on a
superclass of the receiver's class.
MyClass>>processObject: anObject
self doThisWithObject: anObject.
self doThatToObject: anObject.
If a method needs to call on a support method to do some work, send the message to self. In fact, a good rule
of thumb is, if you can't figure out what object to send the message to, send it to self.
-->
===супер===
|