问题
I'm reading through Seven Programming Languages in Seven Weeks, and one of the problems states:
How would you change /
to return 0
if the denominator is zero?
I first tried defining my own /
and proxying its implementation to the original /
method like this:
Number oldSlash := Number getSlot("/")
Number / = method(x, Number oldSlash(x))
However that was not working for me. After doing some Googling I found a similar piece of code. The code I found was using self
in the implementation of the method. So, I tried using self
and it seemed to work just fine:
Number oldSlash := Number getSlot("/")
Number / = method(x, self oldSlash(x))
My question is: Why does this work when the keyword self
is used, and why does it not work when Number
is used instead?
回答1:
The short version:
Number
is a "base class" for numbers; not an actual numerical value. You can't use it for mathematical operations. self
represents the object your method was invoked on, which turns out to be the number you want to use as numerator in your division.
The longer version:
First, some background: Division as you know takes two arguments. The method you're defining only takes one argument (the x
). The other argument is implicit and it's the Number you're invoking the division on. To make it crystal clear, when you're writing a / b
the method /
is invoked on the object a
and it gets passed the value b
as parameter. In a more C-like language, you'd say something like a.divide(b)
. You don't pass a
as a parameter, but it is accessible from the function anyway, as self
.
So, using what we know from above, writing self oldSlash(x)
performs division using self
as numerator and x
as denominator. The value of self
is set when your "newSlash" method is called, once again implicitly to the object you're calling the method on. If you're familiar with JavaScript, self
is Io's name for this
.
When instead you write Number oldSlash(x)
you use the object Number
as the numerator in the division. Number
is not an actual number, but rather the "base class" for all numbers. It does not have a value. Hence you cannot perform mathematical operations on it.
回答2:
From the Io Programming Guide
All methods (except new) have the structure (the "object") as the first argument the variable is named "self".
But you can omit self
, is implicit:
Number oldSlash := Number getSlot("/")
Number / = method(x, oldSlash(x))
来源:https://stackoverflow.com/questions/8282911/whats-the-significance-of-self-inside-of-a-method