What's the significance of self inside of a method?

天大地大妈咪最大 提交于 2019-12-06 03:46:32

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.

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))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!