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

Following are the list of members of the Function constructor:

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 sent 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, ...)

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

Following are the ECMAScript 5 addition to a Function constructor:

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]"   

ECMAScript 6 additions to a Function

Following are the ECMAScript 6 addition to a Function constructor:

Arrow Functions

An arrow function expression has a shorter syntax compared to function expressions and does not bind its own this, arguments, super, or new.target. Arrow functions are always anonymous.

    () => { ... }
    // no parameter 
    x => { ... }
    // one 
    parameter, an
    identifier 
    (x, y) => 
    {   ... }
    // several
    parameters
    const squares =
    [1, 2, 3].map(
    x => x * x);   

Statement Bodies are more expressive and concise closure syntax

    arr.forEach(v =>
    { if (v % 5 
     ===0)
filtered:ist.push(v)
    })   

..................Content has been hidden....................

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