Function overloading in JavaScript

I won’t talk about PHP today. Sorry PHPers. If you do some fron­tend job, you won’t be disap­po­in­ted. I’m assu­ming you know some basic Java­Script stuff like closu­res, proto­ty­ping and context swit­ching, because I’m going to do some cheating.

Our goal for today is to force Java­Script to invoke diffe­rent func­tions accor­ding to diffe­rent argu­ments number. To further compli­cate all of this, we’ll work on proto­ty­pes and check if over­lo­ading works on inhe­ri­ted objects.

I’ll use Coffe­eScript since it has nice, conden­sed syntax. You don’t need to write much JS boiler­plate like semi­co­lons and braces, what leads to about 30% less code in CS <-> JS compa­ri­son. Always remem­ber: Coffe­eScript is just Java­Script and you can simple paste it in Try Coffe­eScript’s section to see the JS compi­led result. Don’t worry, i’ll provide some hints in sensi­tive places.

Most impor­tant things for today are:

  • you can always check how many argu­ments func­tion has in its decla­ra­tion using length property,
  • you can always check how many argu­ments func­tion was invo­ked with by using arguments.length property.


A few ending thoughts:

  • augmen­ting methods have some perfor­mance penalty,
  • you’ll proba­bly compli­cate stuff when use over­lo­ading too much,
  • if you truly need that solu­tion in JS, you’re doing some­thing wrong :-)

Podobne wpisy:

  1. Play­ing with PHP func­tio­nal way
  2. Creating EAN-13 barcode using Coffe­eScript and HTML5 Canvas
  3. Wygrze­bane z GitHuba (5) : CoffeeConsole
  4. 2 ways to check stream mimetype

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany.

Możesz użyć następujących tagów oraz atrybutów HTML-a: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <p> <pre lang="" line="" escaped=""> <q cite=""> <strike> <strong>