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 |
|
|
Allows you to call another function while overwriting the other function's function whatIsIt(){
return this.toString();
}
> var myObj = {};
> whatIsIt.apply(myObj);
"[object Object]"
> whatIsIt.apply(window);
"[object Window]"
|
|
|
Same as |
|
|
The number of parameters the function expects: > parseInt.length;
2
If you forget the difference between
> Function.prototype.call.length;
1
> Function.prototype.apply.length;
2
The
|
ECMAScript 5 additions to a Function
Following are the ECMAScript 5 addition to a Function constructor:
|
Property/method |
Description |
|
|
When you want to call a function that uses this internally and you want to define what this is. The methods > 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
|
() => { ... }
// 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)
})
|