When animal behavior varies by type, multi creates a multimethod: a callable function whose dispatch function selects the matching implementation without requiring objects. section 13.2
A multimethod combines:
- A dispatch function that receives the arguments and returns a dispatch value such as "dog", "cat", or "cow". section 13.2
- Methods registered for particular dispatch values, plus an optional default implementation. section 13.2
Greeting animals
Create greet with multi(greetDispatch), register greetDog, greetCat, and greetCow, then call greet(myDog), greet(myCat), or greet(myCow) like a regular function. A default method handles an unfamiliar horse. section 13.2
Listing 13.6 The dispatch function for greet multimethod
function greetDispatch(animal) { #1
if(dev()) {
if(!ajv.validate(animalSchema, animal)) { #2
var errors = ajv.errorsText(ajv.errors);
throw ("greet called with invalid arguments: " + errors);
}
}
return animal.type; #3
}
var greet = multi(greetDispatch); #4
Inspect the dispatch function and the point where multi creates greet. section 13.2
