函数声明 (函数语句) 定义函数采用指定参数。
还可以定义函数使用
Function
构造函数和
函数表达式
.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
function name([param[, param,[..., param]]]) {
[statements]
}
name
函数名称。
param
可选
要被传递给函数的自变量名称。最大自变量数在不同引擎中有所不同。
statements
可选
包含函数本体的语句。
采用函数声明创建的函数是
Function
对象且拥有所有特性、方法及行为在
Function
对象。见
Function
了解函数的详细信息。
也可以使用表达式创建函数 (见
函数表达式
).
默认情况下,函数返回
undefined
。要返回任何其它值,函数必须有
return
语句,指定要返回的值。
可以有条件地声明函数,也就是说,可以把函数语句嵌套在
if
语句,不管怎样,结果跨实现是不一致的,因此不应该在生产代码中使用此模式。对于条件函数的创建,使用函数表达式代替。
var hoisted = "foo" in this;
console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
if (false) {
function foo(){ return 1; }
}
// In Chrome:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Firefox:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Edge:
// 'foo' name is not hoisted. typeof foo is undefined
//
// In Safari:
// 'foo' name is hoisted. typeof foo is function
The results are exactly the same for a condition that evaluates to true
var hoisted = "foo" in this;
console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
if (true) {
function foo(){ return 1; }
}
// In Chrome:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Firefox:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Edge:
// 'foo' name is not hoisted. typeof foo is undefined
//
// In Safari:
// 'foo' name is hoisted. typeof foo is function
JavaScript 函数声明被提升到封闭函数或全局作用域的顶部。可以使用函数在声明它之前:
hoisted(); // logs "foo"
function hoisted() {
console.log('foo');
}
注意,
function expressions
未提升:
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log('bar');
};
function
以下代码声明的函数返回总销售额,当给定产品单元销售数
a
,
b
,和
c
.
function calc_sales(units_a, units_b, units_c) {
return units_a * 79 + units_b * 129 + units_c * 699;
}
| 规范 |
|---|
|
ECMAScript (ECMA-262)
在该规范中的 Function definitions 定义。 |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
function
|
Chrome 1 | Edge 12 | Firefox 1 | IE 3 | Opera 3 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 | nodejs 0.1.100 |
| Trailing comma in parameters | Chrome 58 | Edge 14 | Firefox 52 | IE No | Opera 45 | Safari 10 | WebView Android 58 | Chrome Android 58 | Firefox Android 52 | Opera Android 43 | Safari iOS 10 | Samsung Internet Android 7.0 | nodejs 8.0.0 |
完整支持
不支持