17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sample: sample77.html<br />

<br />

var addFunction = new Function('num1', 'num2', 'return num1 + num2');<br />

*/<br />

/* Alternately, a single comma-separated string with arguments can be<br />

the first parameter of the constructor, with the function body following.<br />

var timesFunction = new Function('num1,num2', 'return num1 * num2');<br />

console.log(addFunction(2, 2), timesFunction(2, 2)); // Logs '4 4'<br />

// Versus the more common patterns for instantiating a function:<br />

var addFunction = function (num1, num2) { return num1 + num2; }; //<br />

Expression form.<br />

function addFunction(num1, num2) { return num1 + num2; } // Statement<br />

form.<br />

<br />

Notes<br />

Directly leveraging the Function() constructor is not recommended or typically ever<br />

done because <strong>JavaScript</strong> will use eval() to parse the string containing the function’s<br />

logic. Many consider eval() to be unnecessary overhead. If it’s in use, a flaw in the<br />

design of the code is highly possible.<br />

Using the Function() constructor without the new keyword has the same effect as<br />

using only the constructor to create function objects (e.g., new Function('x','return<br />

x') vs. function(('x','return x')).<br />

No closure is created (see Chapter 7) when invoking the Function() constructor<br />

directly.<br />

Function() properties and methods<br />

The function object has the following properties (not including inherited properties and<br />

methods):<br />

Properties (e.g., Function.prototype;):<br />

prototype<br />

90

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

Saved successfully!

Ooh no, something went wrong!