Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

The Function( ) Constructor and Function Literals

As we saw in Chapter 7, there are two ways to define functions other than the basic function statement. As of JavaScript 1.1, functions can be defined using the Function( ) constructor, and in JavaScript 1.2 and later, they can be defined with function literals. You should be aware of some important differences between these two techniques.

First, the Function( ) constructor allows JavaScript code to be dynamically created and compiled at runtime. Function literals, however, are a static part of program structure, just as function statements are.

Second, as a corollary of the first difference, the Function( ) constructor parses the function body and creates a new function object each time it is called. If the call to the constructor appears within a loop or within a frequently called function, this process can be inefficient. On the other hand, a function literal or nested function that appears within a loop or function is not recompiled each time it is encountered. Nor is a different function object created each time a function literal is encountered. (Although, as noted earlier, a new closure may be required to capture differences in the lexical scope in which the function is defined.)

The third difference between the Function( ) constructor and function literals is that functions created with the Function( ) constructor do not use lexical scoping; instead, they are always compiled as if they were top-level functions, as the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata