11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

}<br />

}<br />

inner1(); // this will error because inner1 is local to testFunction<br />

While using local functions provides us with some ability to create stand-alone modules of<br />

code, such techniques are rarely seen in <strong>JavaScript</strong>. Part of the reason is that local (or<br />

―nested‖) functions have been supported only since the 4.x generation of browsers. <strong>The</strong> other<br />

reason, of course, is that unfortunately most <strong>JavaScript</strong> programmers do not practice such<br />

modular coding styles.<br />

Functions as Objects<br />

As we‘ll see in the next chapter, in <strong>JavaScript</strong> just about everything that is not primitive data is<br />

an object, and functions are no exception. Thus, it is possible to define functions in a much<br />

different way than we have seen up until now, by using the keyword new and the Function<br />

object. For example, here we define a function and assign it to the variable sayHello. Notice<br />

that Function is capitalized, as we are talking about creating an instance of <strong>JavaScript</strong>‘s built-in<br />

Function object:<br />

var sayHello = new Function("alert('Hello there');");<br />

Later on we can then use the assigned variable sayHello just like a regular function call:<br />

sayHello();<br />

Because functions are first-class data types, the function can even be assigned to another<br />

variable and used by that name instead.<br />

var sayHelloAgain = sayHello;<br />

sayHelloAgain();<br />

To expand the example, we could define a function with a parameter to print out<br />

var sayHello2 = new Function("msg","alert('Hello there '+msg);");<br />

and call it:<br />

sayHello2('Thomas');<br />

<strong>The</strong> general syntax for the Function() constructor is<br />

var functionName = new Function("argument 1",..."argument n",

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!