Tuesday, October 30, 2012

Functions as objects in Javascript

In Javascript, functions are objects.

That statement probably comes off a little underwhelming. Let's look at an example.

function addTheNumbers(num1, num2) {
    return num1 + num2;
}

function subtractTheNumbers(num1, num2) {
    return num1 - num2;
}

var func; 

func = addTheNumbers;
var result1 = func(1, 2); // 3

func = subtractTheNumbers;
var result2 = func(1, 2); // -1

We defined two different functions, one for adding and one for subtracting. Both take the same number of parameters. We then separately assign each of the functions to another variable, and then call that variable. You can point to any function just by using the name of that function as a variable.

For more information, check out our website.

1 comment: