Description of the function
Functions are a core concept for any language. Functions can encapsulate any number of statements and can be invoked anywhere and at any time. In JavaScript, functions are objects that programs can manipulate at will. Functions can be defined nested within other functions so that they can access any variable in the scope in which they were defined, which gives JavaScript great programming power.
Declaration of functions
JavaScript has three ways of declaring functions
(1) declaration statement of function
The block of code declared by the function command is a function. The function command is followed by the function name, which is followed by a pair of parentheses containing the parameters of the function passed in. The body of the function is enclosed in braces.
function hello(a){
console.log(a);
}
Copy the code
The above code names a hello function that can be called later using the form Hello (). This is called Function Declaration.
(2) Function expression
In addition to declaring functions with the function command, you can also write variable assignments
var hello = function(a){
console.log(a)
}
Copy the code
This writing assigns an anonymous function to a variable. In this case, the anonymous Function is also called Function Expression because only expressions can be placed on the right side of the equal sign of an assignment statement.
When a function is declared using a function expression, the function command is not followed by the function name. If a function name is added, the function name is only valid inside the function body, not outside it.
var hello = function x(a){
console.log(typeof x);
}
console.log(x);// ReferenceError: x is not defined
hello(); //function
Copy the code
For a named function expression, the function name is equivalent to the parameter of the function object and can only be used inside the function. The variable name is the argument of the function object and can be used both inside and outside the function
var test = function fn(){
return fn === test;
}
console.log(test());//true
console.log(test === fn);//ReferenceError: fn is not defined
Copy the code
(3) Function constructor
var add = new Function(
'x'.'y'.'return x + y'
);
/ / is equivalent to
function add(x,y){
return x + y;
}
Copy the code
In the above code, the Function constructor takes three arguments, all of which are arguments to the add Function except that the last argument is the “body” of the add Function.
You can pass as many arguments to the Function constructor as you want. Only the last argument is considered the Function body. If there is only one argument, that argument is the Function body.
var foo = new Function(
'return "hello world"'
);
/ / is equivalent to
function foo() {
return 'hello world';
}
Copy the code
The Function constructor can omit the new command and return exactly the same result.
In general, this way of declaring functions is very unintuitive and rarely used.
Function return value
A return statement in a function is used to return the value returned after the function is called. A return statement can only appear inside a function. Otherwise, the syntax is incorrect
return 1;//SyntaxError: Illegal return statement
Copy the code
If there is no return statement, the function call simply executes each statement in the body of the function until the function terminates and returns to the caller. In this case, the result of calling the expression is undefined
var test = function fn(){}
console.log(test());//undefined
Copy the code
The function terminates when a return statement is executed
var test = function fn(){
return 2;
};
console.log(test());/ / 2
Copy the code
Note: Not all statements following a return statement ina function are not executed, except finally statements, which do not prevent the finally clause from executing
function testFinally(){
try{
return 2;
}catch(error){
return 1;
}finally{
return 0; }}Copy the code
try{
// Generally speaking, the code here will go from beginning to end without any problems
But sometimes an exception is thrown, either directly by the throw statement or indirectly by calling a method
}catch(e){
// This code is executed if and only if the try block throws an exception
// We can use the local variable e to get a reference to the Error object or any other value thrown
// The code block here can handle the exception for whatever reason, ignore it, or rethrow it with a throw statement
}finally{
// The logic in finally always executes whether or not a try statement throws an exception. The ways to terminate a try block are:
//1. Execute the last statement in the block
//2. Terminate with a break, continue or return statement
//3, throw an exception, the exception is caught by the catch clause
//4, throw an exception, the exception is not caught, continue to propagate
}
Copy the code
A function can have multiple return statements
function compare(x,y){
if(x > y){
return x - y;
}else{
returny - x; }}Copy the code
The return statement can be used alone without expression, which also returns undefined to the calling program.
var test = function fn(){
return;
}
console.log(test()); //undefined;
Copy the code
A return statement is often the last statement in a function because it can be used to make the function return earlier. When a return is executed, the function immediately returns without executing the rest of the statement
// Does not pop 1
var test = function fn(){
return;
alert(1);
};
console.log(test());//undefined
Copy the code
If the function is called prefixed with new and the return value is not an object or has no return value, this(the new object) is returned.
function fn(){
this.a = 2;
return 1;
}
var test = new fn();
console.log(test);//{a:2}
console.log(test.constructor);//fn(){this.a = 2; return 1; }
Copy the code
Returns an object if the return value is an object
function fn(){
this.a = 2;
return {a:1};
}
var test = new fn();
console.log(test);//{a:1}
console.log(test.constructor);//Object() { [native code] }
Copy the code
A function call
It is executed only when the function is called. A call operator is a pair of parentheses followed by any expression that produces a function value. The parentheses may contain zero or more comma-separated expressions. Each expression produces a parameter value, and each parameter value is assigned the name of the parameter defined when the function is declared
There are four JavaScript invocation modes: function invocation, method invocation, constructor invocation, and indirect invocationCopy the code
[1] Function call mode
When a function is not a property of an object, it is called as a function. For normal function calls, the return value of the function is the value of the calling expression
function add(x,y){
return x+y;
}
var sum = add(3.4);
console.log(sum)/ / 7
Copy the code
When a function is called using function call mode, in non-strict mode, this is bound to the global object; In strict mode, this is undefined
function add(x,y){
console.log(this);//window
}
add();
Copy the code
function add(x,y){
'use strict';
console.log(this);//undefined
}
add();//window
Copy the code
rewrite
Because this in the function call pattern is bound to the global object, the global attribute is overridden
var a = 0;
function fn(){
this.a = 1;
}
fn();
console.log(this.this.a,a);//window 1 1
Copy the code
So, be careful to avoid problems with global property overrides
[2] Method call pattern
When a function is stored in an object property, we call it a method. When a method is called, this is bound to that object. If the calling expression contains an action to extract a property, it is called as a method
var o = {
m:function(){
console.log(111);
}
}
p.m();
Copy the code
A method can use this to access its own object, so it can evaluate or modify the object. The binding of this to the object occurs at call time. Methods that use this to get the context of the object they belong to are called public methods.
var p = {
a:1.m:function(){
console.log(111);
},
n:function(){
this.a = 2; }}console.log(p.m()); / / 1
o.n();
console.log(o.m().a);/ / 2
Copy the code
[3] Constructor call pattern
If a function or method call is preceded by the keyword new, it constitutes a constructor call
function fn(){
this.a = 1;
};
var obj = new fn();
console.log(obj.a);/ / 1
Copy the code
If the constructor call contains a list of arguments in parentheses, the argument expressions are evaluated and passed into the function
function fn(x){
this.a = x;
};
var obj = new fn(2);
console.log(obj.a);/ / 2
Copy the code
The javascript constructor call syntax allows omitting the argument list and parentheses if the constructor has no parameters. Any constructor call with no parameters can omit the parentheses
var o = new Object(a);/ / equivalent to the
var o = new Object;
Copy the code
Constructors usually do not use the return keyword. They usually initialize new objects and return explicitly when the body of the constructor is finished executing. In this case, the constructor call expression evaluates to the value of the new object.
function fn(){
this.a = 2;
}
var test = new fn();
console.log(test);//{a:2}
Copy the code
If the constructor uses a return statement without specifying a return value, or if it returns a primitive value, the return value is ignored and the new object is used as the result of the call
function fn(){
this.a = 2;
return;
}
var test = new fn();
console.log(test);//{a:2}
Copy the code
If the constructor explicitly returns an object using a return statement, the value of the calling expression is that object
var obj = {a:1};
function fn(){
this.a = 2;
return obj;
}
var test = new fn();
console.log(test);//{a:1}
Copy the code
[4] Indirect invocation mode
Functions in javascript are also objects, and function objects can also contain methods. The call() and apply() methods can be used to call functions indirectly
Both of these methods allow you to explicitly specify the value of this required for the call, that is, any function can be called as a method of any object, even if the function is not a method of that object. Either method can specify the arguments to the call. The call() method uses its own list of arguments as arguments to the function, while the apply() method requires that arguments be passed in as arrays
var obj = {};
function sum(x,y){
return x+y;
}
console.log(sum.call(obj,1.2));/ / 3
console.log(sum.apply(obj,[1.2]));/ / 3
Copy the code
For the call() and apply() methods, we’ll focus on the properties and methods of functions in later sections.
Function parameters
Arguments to javascript functions are different from arguments to functions in most other languages. It doesn’t care how many arguments are passed in, it doesn’t care what data type is passed in, it doesn’t even care what arguments are passed in, okay
arguments
The function definition in javascript does not specify the type of the function parameter, nor does the function call do any type checking on the argument value passed in. In fact, javascript function calls don’t even check the number of parameters passed in.
function add(x){
return x+1;
};
console.log(add(1));/ / 2
console.log(add('1'));/ / '11'
console.log(add());//NaN
console.log(add(1.2));/ / 2
Copy the code
The same parameters
In non-strict mode, a parameter of the same name can appear in a function, and only the last parameter of that name can be accessed
function add(x,x,x){
return x;
}
console.log(add(1.2.3));/ / 3
Copy the code
In strict mode, a namesake throws a syntax error
function add(x,x,x){
'use strict';
return x;
}
console.log(add(1.2.3));//SyntaxError: Duplicate parameter name not allowed in this context
Copy the code
Number of parameters
When there are fewer arguments than the number specified in the function declaration, the remaining parameters are set to undefined
function add(x,y){
console.log(x,y);//1 undefined
}
add(1);
Copy the code
When there are more arguments than parameters, there is no way to get the rest of the arguments directly; you need to use the Arguments object
Arguments in javascript are internally represented by an array. The function always receives the array, regardless of the parameters in the array. The arguments array can be accessed inside the function body via the arguments object to get each argument passed to the function. The Arguments object is not an instance of Array; it is an array-like object, each of whose elements can be accessed using square bracket syntax.
function add(x){
console.log(arguments[0].arguments[1].arguments[2])/ / 1 2 3
return x+1;
}
add(1.2.3);
Copy the code
The length property of the arguments object shows the number of arguments, and the length property of the function shows the number of parameters
function add(x,y){
console.log(arguments.length)/ / 3
return x+1;
}
add(1.2.3);
console.log(add.length);/ / 2
Copy the code
Parameters are convenient, but not necessary
function add(){
return arguments[0] + arguments[1];
}
console.log(add(1.2));/ / 3
Copy the code
Function overloading
JavaScript functions cannot be overloaded in the traditional sense. In other languages, it is possible to write two definitions for a function, as long as the signatures (the types and number of arguments that they accept) are different
Javascript functions have no signature because their arguments are represented by arrays of zero or more values. True overloading is impossible without a function signature
// The following declaration overwrites the previous declaration
function addSomeNumber(num){
return num + 100;
}
function addSomeNumber(num){
return num + 200;
}
var result = addSomeNumber(100);/ / 300
Copy the code
Method overloading can only be mimicked by checking the type and number of arguments passed into the function and reacting differently
function doAdd(){
if(arguments.length == 1){
alert(arguments[0] + 10);
}else if(arguments.length == 2){
alert(arguments[0] + arguments[1]);
}
}
doAdd(10);/ / 20
doAdd(30.20);/ / 50
Copy the code
Parameter passing
Arguments to all functions in javascript are passed by value. That is, copying a value from outside a function to an argument inside a function is the same as copying a value from one variable to another
[1] Basic type values
When passing a value of a primitive type to a parameter, the passed value is copied to a local variable (an element of the named parameter or arguments object)
function addTen(num){
num += 10;
return num;
}
var count = 20;
var result = addTen(count);
console.log(count);//20, no change
console.log(result);/ / 30
Copy the code
[2] Reference type values
When you pass a value of a reference type to a parameter, the value’s in-memory address is copied to a local variable, so changes to the local variable are reflected outside the function
function setName(obj){
//obj is a local variable inside a function
obj.name = 'test';
}
var person = new Object(a); setName(person);console.log(person.name);//'test'
Copy the code
When a parameter of a reference type is overridden inside a function, the variable refers to a local object. The local object is destroyed immediately after the function completes execution
function setName(obj){
obj.name = 'test';
console.log(person.name);//'test'
// The function internally overrides the parameter of the reference type. The obj variable is a local object. The function is destroyed immediately after execution. So person.name is still the property value of the global object Person
obj = new Object(a); obj.name ='white';
console.log(person.name);//'test'
}
var person = new Object(a); setName(person);Copy the code
Function properties and methods
Functions are special objects in javascript that can have properties and methods just like normal objects have properties and methods. You can even use the Function() constructor to create new Function objects.
attribute
Length attribute
As mentioned in the previous section, the length property of the Arguments object represents the number of arguments, and the length property of the arguments object represents the number of parameters
function add(x,y){
console.log(argument.length);/ / 3
console.log(add.length);/ / 2
}
add(1.2.3);
Copy the code
The name attribute
The function defines a nonstandard name attribute through which to access the name specified by the given function. The value of this attribute is always equal to the identifier following the function keyword. The name attribute of anonymous functions is null
function fn(){};
console.log(fn.name);//'fn'
var fn = function(){};
console.log(fn.name);//'fn'
var fn = function abc(){};
console.log(fn.name);//'abc'
Copy the code
The prototype property
Each function has a Prototype property that points to a reference to an object called a Prototype object. Each function contains a different prototype object. When a function is used as a constructor, the newly created object inherits properties from the prototype object.
function fn(){};
var obj = new fn;
fn.prototype.a = 1;
console.log(obj.a);/ / 1
Copy the code
The prototype object is going to be a very important lesson later in our object-oriented programming course.
methods
The apply () and call ()
Each function contains two non-inherited methods: the apply() and call() methods. The purpose of both methods is to call a function in a particular scope, essentially equal to the value of the this object in the function body.
To call function f() on object O, use call() and apply()
f.call(o);
f.apply(o);
Copy the code
Assuming that m method does not exist in o, it is equivalent to:
o.m = f;// a temporary method to store f as o
o.m();// Call it without passing in arguments
delete o.m; // Delete temporary methods
Copy the code
Example:
window.color = "red";
var o = {color: "blue"};
function sayColor(){
console.log(this.color);
}
sayColor(); //red
sayColor.call(this); //red
sayColor.call(window); //red
sayColor.call(o); //blue
Copy the code
Saycolor.call (o) = saycolor.call (o)
o.sayColor = sayColor;
o.sayColor(); //blue
delete o.sayColor;
Copy the code
The apply() method takes two arguments: the scope in which the function is run (or the parent object of the function to be called, which is the calling context and is referred to by this in the function body), and the array of arguments. The second argument can be an instance of Array or arguments object
function sum(num1, num2){
return num1 + num2;
}
// Since the scope of the running function is global, this represents the window object
function callSum1(num1, num2){
return sum.apply(this.arguments);
}
function callSum2(num1, num2){
return sum.apply(this, [num1, num2]);
}
console.log(callSum1(10.10));/ / 20
console.log(callSum2(10.10));/ / 20
Copy the code
The call() method does the same thing as the apply() method; they differ only in the way they receive arguments. For the call() method, the first argument is that the value of this does not change, except that the rest of the arguments are passed directly to the function. In other words, when using the call() method, the arguments passed to the function must be enumerated one by one
function sum(num1, num2){
return num1 + num2;
}
function callSum(num1, num2){
return sum.call(this, num1, num2);
}
console.log(callSum(10.10)); / / 20
Copy the code
Whether to use apply() or call() depends entirely on which function is the most convenient way to pass parameters. If you plan to pass arguments objects directly, or if you include a function that receives an array first, then it’s definitely more convenient to use apply(); Otherwise, call() might be more appropriate
In non-strict mode, null or undefined values are converted to global objects when a function’s call() or apply() method is used. In strict mode, the function’s this value is always the specified value
var color = 'red';
function displayColor(){
console.log(this.color);
}
displayColor.call(null);//red
Copy the code
var color = 'red';
function displayColor(){
'use strict';
console.log(this.color);
}
displayColor.call(null);//TypeError: Cannot read property 'color' of null
Copy the code
application
[1] Find the largest element in the array
JavaScript does not provide a function to find the largest element in an array. Using the apply method in combination with the math.max () method, you can return the largest element of the array
var a = [10.2.4.15.9];
Math.max.apply(null, a);/ / 15
Copy the code
[2] Convert class arrays into real arrays
Array.prototype.slice.apply({0:1.length:1});/ / [1]
Copy the code
[3] Array append
var a = [];
Array.prototype.push.apply(a,[1.2.3]);
console.log(a);/ / [1, 2, 3]
Array.prototype.push.apply(a,[2.3.4]);
console.log(a);/ /,2,3,2,3,4 [1]
Copy the code
[4] Use call and apply for inheritance
function Person(name,age){
// This refers to instances
this.name = name
this.age = age
this.sayAge = function(){
console.log(this.age)
}
}
function female(){
Person.apply(this.arguments)// All methods of the parent element are inherited by executing them once
}
var dot = new Female('Dot'.2)
Copy the code
[5] Use the log agent console.log
function log(){
console.log.apply(console.arguments);
}
Var log = console.log()
Copy the code
bind()
Bind () is a new method in ES5 that binds a function to an object
When the bind() method is called on function f() with an object o as an argument, the method returns a new function. Calling a new function as a function call will call the original function f() as if it were o, and any arguments passed to the new function will be passed to the original function
function f(){
return this.x + y;// This is the function to bind
}
var o = {x : 1};// The object to bind
var g = f.bind(o);// Call o.f(x) by calling g(x);
g(2);/ / 3;
Copy the code
The bind() method not only binds a function to an object, it also comes with some other applications: in addition to the first argument, arguments passed to bind bind() can also be bound to this. This attached application is a common functional programming technique, sometimes called ‘currying’.
var sum = function(x,y){
return x+y;
}
var succ = sum.bind(null.1);
succ(2); //3, x is bound to 1, and 2 is passed as argument y
Copy the code
function f(y,z){
return this.x + y + z;
}
var g = f.bind({x:1},2);
g(3); //6, this.x to 1, y to 2, z to 3
Copy the code
Currization using the bind() method splits function arguments
function getConfig(colors,size,otherOptions){
console.log(colors,size,otherOptions);
}
var defaultConfig = getConfig.bind(null.'#c00'.'1024 * 768');
defaultConfig('123');//'#c00 1024*768 123'
defaultConfig('456');//'#c00 1024*768 456'
Copy the code