website statistics

Forth bound methodsΒΆ

You can think of CREATE DOES> as the creator of an object with a single bound method.

: counter
    create 0 ,
    does>  1 over +! @ ;
counter apple

Here counter is the constructor word - it constructs a zero-based counter - and apple is its method. More exactly, apple is a bound method, it is tied to the object itself, so does not need an object parameter:

apple . apple . apple .
0 1 2 ok

But what about multiple methods on the object? Use multiple CREATE DOES> words, one for each method. All the methods need to share the same object, so an extra level of indirection is necessary.

: up   create dup , does> @ 1 over +! @ ;
: down create dup , does> @ -1 over +! @ ;
: counter
    here 0 ,
    up down
    drop
;
counter +banana -banana

Or even:

: method>
    postpone create postpone dup postpone ,
    postpone does> postpone @
; immediate

: up    method> 1 over +! @ ;
: down  method> -1 over +! @ ;
: counter
    here 0 ,
    up down
    drop
;

counter +banana -banana