JavaScript binding, function apply, function call

December 28, 2012

In JavaScript, binding is always explicit, and can be easily lost, so a method using “this” will not refer to the proper object in all situations, ¬†unless you force it to.

JavaScript provides two options to do explicit binding “apply” and “call”.

Apply

Every JavaScript function is equipped with “apply” method that allows you to call the function with specific binding. I takes two arguments, the binding object and an array of arguments to be passed to the function.

fun.apply(thisArg[, argsArray])

Call

“Call” method is similar to “apply”, but it takes the arguments themselves not an array.

fun.call(thisArg[, arg1[, arg2[, ...]]])

References

http://www.alistapart.com/articles/getoutbindingsituations

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call

http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this


JavaScript function declaration, function expression, Function constructor, Anonymous function

December 25, 2012

Function declaration –

function name([param[, param[, ... param]]]) {
   statements
}
example -
function sum(a, b)
{
    return a + b;
}

name – The function name

param – The name of the argument to be passed to the function. A function can have up to 255 arguments.

statements – The body of the function

Function expression and Anonymous function –

function [name]([param] [, param] [..., param]) {
   statements
}
example -
var sum = function(a, b) { return a + b; }

The name can be omitted in which case it becomes anonymous function.
Anonymous functions can help make code more concise when declaring a function that will only be used in one place.

Function constructor –

Function objects can be created with new operator

new Function (arg1, arg2, ... argN, functionBody)

example - 
var sum = new Function('a','b', 'return a + b;');

arg1, arg2, … argN – zero or more names to be used by the function as argument names

functionBody – A string containing JavaScript statements forming the function body.

References
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope

http://helephant.com/2008/08/23/javascript-anonymous-functions/

http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work