The self Keyword
In Program 7.4, we decided to reduce the fraction outside of the add: method. We could have done it inside add: as well; the decision was completely arbitrary. However, how would we go about identifying the fraction to be reduced? What fraction do we want to reduce anyway? We want to reduce the same fraction that we sent the add: message to.
We know how to identify instance variables inside a method directly by name, but we don’t know how to directly identify the receiver of the message. Luckily, there is a way to do that.
You can use the keyword self to refer to the object that is the receiver of the current message. If inside your add: method you wrote
[self reduce];
the reduce method would be applied to the Fraction object ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access