JavaScript學習之function與Function區別
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are objects.
Description
Every function in JavaScript is a Function
Function
for
information on properties and methods of Function
objects.
To return a value other than the default, a function must have a statement
that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called
with the
keyword,
the default value is the value of its this
parameter. For all other functions,
the default return value is undefined
.
The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:
/* Declare the function 'myFunc' */
function myFunc(theObject) {
theObject.brand = "Toyota";
}
/*
* Declare variable 'mycar';
* create and initialize a new Object;
* assign reference to it to 'mycar'
*/
var mycar = {
brand: "Honda",
model: "Accord",
year: 1998
};
/* Logs 'Honda' */
console.log(mycar.brand);
/* Pass object reference to the function */
myFunc(mycar);
/*
* Logs 'Toyota' as the value of the 'brand' property
* of the object, as changed to by the function.
*/
console.log(mycar.brand);
The this
keyword does
not refer to the currently executing function, so you must refer toFunction
objects
by name, even within the function body.
Defining functions
There are several ways to define functions:
The function declaration (function
statement)
There is a special syntax for declaring functions (see function statement for details):
function name([param[, param[, ... param]]]) { statements }
name
- The function name.
param
- The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements
- The statements comprising the body of the function.
The function expression (function
expression)
A function expression is similar to and has the same syntax as a function declaration (seefunction expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are nothoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.
function [name]([param[, param[, ... param]]]) { statements }
name
- The function name. Can be omitted, in which case the function becomes known as an anonymous function.
param
- The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements
- The statements comprising the body of the function.
Here is an example of an anonymous function expression (the name
is
not used):
var myFunction = function() {
statements
}
It is also possible to provide a name inside the definition in order to create a named function expression:
var myFunction = function namedFunction(){
statements
}
One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.
As we can see, both example do not start with the function
keyword. Statements
involving functions which do not start with function
are function expressions.
When function are used only once, a common pattern is an IIFE (Immediately Invokable Function Expressions).
(function() {
statements
})();
IIFE are function expression that are invoked as soon as the function is declared.
The generator function declaration (function*
statement)
There is a special syntax for generator function declarations (see function*
statement
for details):
function* name([param[, param[, ... param]]]) { statements }
name
- The function name.
param
- The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements
- The statements comprising the body of the function.
The generator function expression (function*
expression)
A generator function expression is similar to and has the same syntax as a generator function declaration (see function*
expression
for details):
function* [name]([param[, param[, ... param]]]) { statements }
name
- The function name. Can be omitted, in which case the function becomes known as an anonymous function.
param
- The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements
- The statements comprising the body of the function.
The arrow function expression (=>)
An arrow function expression has a shorter syntax and lexically binds its this
value
(see arrow functions for details):
([param[, param]]) => { statements } param => expression
param
- The name of an argument. Zero arguments need to be indicated with
()
. For only one argument, the parentheses are not required. (likefoo => 1
) statements or expression
- Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
The Function
constructor
Note: Using the Function
constructor
to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.
As all other objects, Function
objects
can be created using the new
operator:
new Function (arg1, arg2, ... argN, functionBody)
arg1, arg2, ... argN
- Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
functionBody
- A string containing the JavaScript statements comprising the function body.
Invoking the Function
constructor as a function (without using the new
operator)
has the same effect as invoking it as a constructor.
The GeneratorFunction
constructor
Note: GeneratorFunction
is
not a global object, but could be obtained from generator function instance (see GeneratorFunction
for
more detail).
Note: Using the GeneratorFunction
constructor
to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.
As all other objects, GeneratorFunction
objects
can be created using the new
operator:
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
arg1, arg2, ... argN
- Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated
with a comma; for example "
x
", "theValue
", or "a,b
".
functionBody
- A string containing the JavaScript statements comprising the function definition.
Invoking the Function
constructor as a function (without using the new
operator)
has the same effect as invoking it as a constructor.
Function parameters
Default parameters
Default function parameters allow formal parameters to be initialized with default values if no value or undefined
is
passed. For more details, see default parameters.
Rest parameters
The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.
The arguments
object
You can refer to a function's arguments within the function by using the arguments
object.
Seearguments.
- : An array-like object containing the arguments passed to the currently executing function.
- : The currently executing function.
- : The function that invoked the currently executing function.
- : The number of arguments passed to the function.
Defining method functions
Getter and setter functions
You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.
- get
-
Binds an object property to a function that will be called when that property is looked up.
- set
- Binds an object property to a function to be called when there is an attempt to set that property.
Method definition syntax
Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.
var obj = {
foo() {},
bar() {}
};
Function
constructor vs. function declaration vs. function expression
Compare the following:
A function defined with the Function
constructor assigned to the variable multiply:
var multiply = new Function('x'