2008 03 26Delegates from a Javascript standpoint
onmousedown, onresize, onwindowclose
. This is possible because functions in Javascript are first-class : they get treated as equally as numbers, strings, or any object. You can even replace a current object's method with your own, just with existingObject.someMethod = function () { … override behaviour here … }
.
ObjC is a very light superset of C and thus functions get packed away the same as C in a huge blob of binary code, with just an adress to remember them by. But classes are first class in ObjC : you can query them anytime with [SomeClass someMethod], examine their methods, etc. Being written in ObjC, Cocoa will then let you change behaviour or get notifications by supplying a class, containing some specifically-named methods that it will call at the appropriate time : this is a delegate. (Recreating the same functionality in C would be tedious : you'd have to allocate a fixed-size structure containing pointers to functions, that delegate structure being specific to that object only, you'd have to set the ones you want to override to your global functions. In C++, you'd have to inherit from a base delegate class specific for that class expecting that delegate, override the functions you want … PWARK ! Being dynamic, ObjC is much more informal than that and will just check your class for specific methods names. )
Delegation is a way to extend behaviour without having to resort to derivation. Delegation is more flexible than derivation, but less flexible than Javascript's override.
But, as bonus side effects :
- your code will be cleanly stored in an object with very descriptive method names
- you can often use the same object as multiple delegates — In Webkit delegates, you can create one object that will be used as a notification recipient for page load, resource load, and resize.
Objective-C from Javascript
- KVC and KVO from a Javascript standpoint
- ObjC protocols from a Javascript standpoint
- Delegates from a Javascript standpoint
- Target+action from a Javascript standpoint
- Outlets from a Javascript standpoint
- Dynamic method over* from a Javascript standpoint
- The Responder Chain from a Javascript standpoint
- PerformSelector from a Javascript standpoint
- NIBs from a Javascript standpoint
- Events from a Javascript standpoint