Skip to content

Chapter 8: Functions

January 28, 2012

This entry is a review of “Chapter 8: Functions” from “JavaScript: The Definitive Guide”

Chapter 8 covers functions in JavaScript. In JavaScript, Functions are specialized Objects, though the typeof operator will for some reason return “function” for them. Most of this material has been covered in other JS books I’ve read (specially JavaScript the Good Parts and JavaScript Patterns), possibly because functions are so central to how JavaScript behaves, but there were still a few interesting bits of info.

The subject is a meaty one, and the chapter does a good job of covering difficult concepts like Closure and Functional programming. Just under 40 pages are dedicated to the topic, and most everything you’d want to know is covered. The end of the chapter focuses on Functional programming, which I’m not a fan of, but it’s still good to get some exposure to it. I’ve found myself using memoization, and have encountered partials in code bases I’ve worked with, so it’s non-essential but good to know stuff.

Below are my notes on what I found interesting in the chapter.

Function constructor

You can apparently create functions directly from the Function constructor. Since functions are objects this makes a lot of since, but it’s still a little strange. This way of creating functions should be avoided since it’s like using eval, and it’ll only create functions in the global scope, not the scope in which you create them. Example usage:

var x = new Function("x", "y", "return x + y;");

bind method

ECMAScript 5 introduces the bind method to the Function prototype. This allows you to create a new function where the inputted object is bound to the “this” parameter of the inputted function.

length property

This was one of those little things I didn’t know about that I thought was kind of neat. Every function has a length property which indicates the number of defined argument parameters.

callee and caller

Former methods of the arguments object. Both are deprecated in strict mode, due to optimization issues. callee allowed you to access the function that was currently being called (useful for anonymous functions). And caller gave you access to the call stack (the function that called the function you’re in).

Callable Objects

Other than functions, there are two other callable objects. Older versions of IE make certain build-in methods like window.alert and document.getElementById callable objects instead of functions (fixed in IE9). And RegExp objects can be invoked, which is a non-standard short-cut way of calling their exec method. This is likely to be discontinued in the future.

From → Chapters

Leave a Comment

Leave a comment