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.

funcE.answer = 'yup'; // Instance property.<br />

console.log(funcE.answer); // Logs 'yup'.<br />

<br />

It is crucial that you realize a function is an object, and thus a value. It can be passed<br />

around or augmented like any other expression in <strong>JavaScript</strong>.<br />

Passing parameters to a function<br />

Parameters are vehicles for passing values into the scope of a function when it is<br />

invoked. In the following sample we invoke addFunction(). Since we have predefined<br />

it to take two parameters, two added values become available within its scope.<br />

Sample: sample81.html<br />

<br />

var addFunction = function (number1, number2) {<br />

var sum = number1 + number2;<br />

return sum;<br />

}<br />

console.log(addFunction(3, 3)); // Logs 6.<br />

<br />

Notes<br />

In contrast to some other programming languages, it is perfectly legal in <strong>JavaScript</strong> to<br />

omit parameters even if the function has been defined to accept these arguments. The<br />

missing parameters are simply given the value undefined. Of course, by leaving out<br />

values for the parameters, the function might not work properly.<br />

If you pass a function unexpected parameters (those not defined when the function was<br />

created), no error will occur. And it's possible to access these parameters from the<br />

arguments object, which is available to all functions.<br />

this and arguments values are available to all functions<br />

Inside the scope and body of all functions, the this and arguments values are<br />

available.<br />

The arguments object is an array-like object containing all of the parameters being<br />

passed to the function. In the following code, even though we forgo specifying<br />

93

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

Saved successfully!

Ooh no, something went wrong!