Function
Overall
Function are objects. It allows properties and methods.
- length: indicate number of named arguments the function expects.
- prototype: actual location of all of the instances.
call:
invoke the function with a specific this value. one is this, the rest are the actual arguments.
function sum(num1, num2){ return num1 + num2; } function callSum(num1, num2){ return sum.call(this, num1, num2); } alert(callSum(10,10)); //20
apply:
invoke the function with a specific this value. two arguments, one is this, the other is the array of arguments.
function sum(num1, num2){ return num1 + num2; } function callSum1(num1, num2){ return sum.apply(this, arguments); //passing in arguments object } function callSum2(num1, num2){ return sum.apply(this, [num1, num2]); //passing in array }
- bind:
create a new function whose this value is bound to the value passed into bind function
window.color = “red”;
var o = { color: “blue” };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue
Defining Functions
function expression
A function expression produces a value - a function object.
var add = function (x, y) { return x + y }; console. log(add(2, 3)); // 5
function declaration
/* function declaration is hoisted completely, variable declaration only partially. */ function add(x, y) { return x + y; }
function Constructor
var add = new Function('x' , 'y' , 'return x + y' );
Function declarations have two advantages over function expressions:
- They are hoisted.
- They have a name.
arguments
Parameter Versus Argument
Parameter are used to define function. Arguments are used to invoke a function.
The arguments
object is an array-like object created when a function is invoked, accessible only inside that function, containing all of the arguments passed into that function. While arguments is array-like, it is not an array. This means that while it has a .length property and numerically-indexed values, it doesn't have any of the Array methods, like .concat or .slice. In order to convert the arguments object into an array, the native Array#slice method is invoked on arguments using call invocation.
In JavaScript, if you specify more arguments than what a function expects, they will be ignored (unless they are accessed via the arguments object). Because of this, no matter how many arguments are passed into the fully bound always Nine function, the result will never change.
Missing or Extra parameters
- The extra parameters are ignored, but can be retrieved via the special array-like variable arguments.
- The missing formal parameters all have the value
undefined