branch14log

Function Wrapping in CoffeeScript

10 Jul 2012

Suppose you want to override a method of a class in CoffeeScript, like you would in Ruby by including a module and then calling super, or by aliasing methods with the once famous alias_method_chain. In JavaScript and subsequently in CoffeeScript you can use Function Wrapping to achive the same effect. And here is an example to show how:
class MyClass
  myMethod: (name) ->
    console.log "hello #{name}"
    
# function wrapping
MyClass::myMethod = ((_super) ->
  (_name) ->
    _super(_name)
    console.log "bye #{_name}"
)(MyClass::myMethod)

(new MyClass).myMethod('Falko')
Happy wrapping.