Function

JavaScript functions are objects. They can be defined using the Function constructor, like so:

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

This is a (generally not recommended) alternative to the function literal (also known as function expression):

var sum = function (a, b) {
  return a + b;
};

Or, the more common function definition:

function sum(a, b) {
  return a + b;
}

The Function.prototype members

Property/Method

Description

apply(this_obj, params_array)

Allows you to call another function while overwriting the other function's this value. The first parameter that apply() accepts is the object to be bound to this inside the function and the second is an array of arguments to be send to the function being called.

function whatIsIt(){
  return this.toString();
}
> var myObj = {};
> whatIsIt.apply(myObj);
"[object Object]"
> whatIsIt.apply(window);
"[object Window]"

call(this_obj, p1, p2, p3, ...)

The same as apply() but accepts arguments one by one, as opposed to as one array.

length

The number of parameters the function expects.

> parseInt.length;
2

If you forget the difference between call() and apply():

> Function.prototype.call.length;
1
> Function.prototype.apply.length;
2

The call() property's length is 1 because all arguments except the first one are optional.

ECMAScript 5 additions to a function

Property/method

Description

Function.prototype.bind()

When you want to call a function that uses this internally and you want to define what this is. The methods call() and apply() invoke the function while bind() returns a new function. Useful when you provide a method as a callback to a method of another object and and you want this to be an object of your choice.

> whatIsIt.apply(window);
"[object Window]"
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.137.64