Autor wpisu: Śpiechu, dodany: 12.04.2014 22:27, tagi: javascript
I won’t talk about PHP today. Sorry PHPers. If you do some frontend job, you won’t be disappointed. I’m assuming you know some basic JavaScript stuff like closures, prototyping and context switching, because I’m going to do some cheating.
Our goal for today is to force JavaScript to invoke different functions according to different arguments number. To further complicate all of this, we’ll work on prototypes and check if overloading works on inherited objects.
I’ll use CoffeeScript since it has nice, condensed syntax. You don’t need to write much JS boilerplate like semicolons and braces, what leads to about 30% less code in CS <-> JS comparison. Always remember: CoffeeScript is just JavaScript and you can simple paste it in Try CoffeeScript’s section to see the JS compiled result. Don’t worry, i’ll provide some hints in sensitive places.
Most important things for today are:
- you can always check how many arguments function has in its declaration using length property,
- you can always check how many arguments function was invoked with by using arguments.length property.
A few ending thoughts:
- augmenting methods have some performance penalty,
- you’ll probably complicate stuff when use overloading too much,
- if you truly need that solution in JS, you’re doing something wrong :-)