Functions

  • A function encloses a set of statements
  • Functions = objects
  • Function objects are linked to Function.prototype (which is itself linked to Object.prototype)

Function Literal

var add = function (a, b) {

        return a + b;

};

Invocation

Invoking a function suspends the execution of the current function, passing control and parameters to the new function. 

In addition to the declared parameters, every function receives two additional parameters: this and arguments.

Invocation Patterns

  • The Method Invocation Pattern
  • The Function Invocation Pattern
  • The Constructor Invocation Pattern
  • The Apply Invocation Pattern

The Method Invocation Pattern

 

this = object

The Function Invocation Pattern

 

this = global

var sum = add(3, 4); 

The Constructor Invocation Pattern

 

this = new object instance

var myQuo = new Quo("confused");

The Constructor Invocation Pattern

 

this = whatever is passed in

var array = [3, 4];

var sum = add.apply(null, array); // sum is 7

Arguments

A bonus parameter that is available to functions when they are invoked is the arguments array. It gives the function access to all of the arguments that were supplied with the invocation

Return

The return statement can be used to cause the function to return early.

 

When return is executed, the function returns immediately without executing the remaining statements.

 

A function always returns a value. If the return value is not specified, then undefined is returned. 

Scope

Closure

http://blog.jhades.org/really-understanding-javascript-closures/

Callbacks

Missed out

  • Recursion
  • Augmenting Types
  • Module
  • Cascade
  • Curry
  • Memoization

Functions

By Bård Hovde

Functions

  • 1,402