Sunday 23 March 2008

Self and Me

A question that comes up a lot in REALbasic is

What is the difference between the Self and Me keywords?
Everybody eventually thinks they have it sorted out in their own minds but it's surprising how many of us then find we're wrong.

I think that essentially it goes something like this:
Self and Me always refer to the same thing, except in the specific instance where you are editing the method handlers of a class in a Window. In those circumstances, Self refers to the item you're editing (the window) and Me refers to the class instance which exposes the method.
The best advice I ever received on this was (I think) from Mars.

If you want to know what Self refers to, while you're coding, look up at the top of the IDE.

If the title bar says
Realbasic - [Untitled] - Class1
then Self refers to Class1. On the other hand, if the title bar says
Realbasic - [Untitled] - Window1
then Self refers to Window1

2 comments:

Anonymous said...

That's really good advice!

I've learned to use the two by looking a little different on the matter. I always use Me when I want to refer to the control I'm editing, so in a buttons action-event, if I refer to Me I know it's the button it self I refer to.

Self on the other hand, I always translate to "Parent", so when editing the same Action event on the same button as before, Self means the buttons "Parent", namely the Window the button is on.

This has served me well until now, but I'm not that experienced and if this method has potential to fail, I'd like to know it so I can change my ways.

Will "my way" be useful always, or am I missing something in my approach perhaps?

Thanks in advance for any advice, and thank you for a great read!

Anonymous said...

Also, REAL Soft could perhaps have chosen a better and more intuitive naming-scheme when adding Me and Self to the language.

But they probably snuck in there when they were needed, and not much thought were given to it's very high potential for confusion.

And changing it now would probably lead to even more confusion :)