determines which implementation to call Single dispatch (JavaScript): a single value is used for dispatch. We’ll look at something new – multiple dispatch. Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 2 / 8
dispatch via an object. jane.describe() Person.prototype.describe = function (...) {...}; Employee.prototype.describe = function (...) {...}; Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 3 / 8
dispatch via an object. jane.describe() Person.prototype.describe = function (...) {...}; Employee.prototype.describe = function (...) {...}; Generic function: dispatch via a function. describe(jane) function describe(self) { if (self instanceof Person) { ... } else if (self instanceof Employee) { ... } } Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 3 / 8
important as this (implicit parameter in single dispatch) Functions become object-oriented, aware of type hierarchy. Benefits: Useful whenever a polymorphic algorithm spans several types: foo(obj1, obj2, obj3) // collaborators, not data In which object should we put the algorithm? Visitor pattern – encapsulate an algorithm: The visitor is a generic function Single dispatch in host is used to trigger visitor methods Axel Rauschmayer (2ality.com) Multiple dispatch 2012-11-30 6 / 8