Tags

There are 4 different ways in which functions can be invoked in JavaScript. The way you invoke determines what the variable “this” evaluates to.

  1. Invoke function without any context i.e. directly calling function as in c programming language (e.g. f();). If function is invoked in this manner then the ‘this’ variable in the function evaluates to global object.
  2. Invoke function in the context of another object, i.e. as a method on an object(e.g. obj.f();). If function is invoked in this manner then the ‘this’ variable evaluates to ‘obj’
  3. Invoke function using new (e.g. var x = new f()). If the function is invoked with new operator then an empty anonymous object is created and ‘this’ variable points to the anonymous object. The anonymous object has a prototype property which points to an object with an constructor property whose value is the function
  4. Invoke function using apply(..) or call(…) method e.g. (f.apply(replacementForthis, argumentsArray) or f.call(replacementForThis, arg1, arg2)). The function f is invoked such that ‘this’ variable is replaced with the value of first parameter and the subsequent arguments are passed as arguments to the function. 

Return value of a function

Function invocation always returns a value, the value returned depends on the type of invocation, for invocations other than new based it returns value of return statement. if there is no return statement or has just empty return statement (like return;) then the returned value is ‘undefined’.

In case the function is invoked with new operator then the return value is ‘this’ object if there is no return statement or return statement returns a non object value. if the return value is an object then that object is returned (e.g  return {a:x}; // returns an object)


function f()
{
return 2;
}
function g()
{
return {a:"x"};
}
var x = new f(); // returns newly created anonymous object
var y = new g(); // returns object {a:"x"}

Advertisements