函数
大约 2 分钟
声明
函数声明:
function showAlert() {
alert('Hello world!');
}
函数表达式:
const showAlert = function () {
alert('Hello world!');
}
还可以使用箭头函数:
const showAlert = () => alert('Hello world!');
变量作用域
- 在函数中声明的变量只在该函数内部可见。
function showAlert() {
const msg = "Hello world!";
alert(msg);
}
console.log(msg); // => undefined
- 函数可以访问和修改外部变量。
const msg = "Hello world!";
function showAlert() {
alert(msg); // => Hello world!
}
- 局部变量优先于外部变量,即如果有同名的局部变量和外部变量,局部变量生效。
const msg = "Bye!";
function showAlert() {
const msg = "Hello world!";
alert(msg); // => Hello world!
}
参数
🔨示例:
function pow(x, n) {
// ...
}
调用它:
pow(3, 5);
声明时可以提供默认值:
function pow(x, n=2) {
// ...
}
pow(3); // => 9
默认值甚至可以是调用一个函数得到的结果。该函数只会在需要使用默认值时被调用:
function getDefaultVal() {
console.log('Hi!');
// ...
}
function pow(x, n=getDefaultVal()) {
// ...
}
pow(3, 2);
pow(3); // => Hi!
声明函数时没有指定参数默认值且调用时没有传入该参数也是可以的,该参数会成为undefined,可以在代码逻辑中对其进行处理。
function pow(x, n) {
if(x === undefined || n === undefined) {
// error!
return;
}
// ...
}
函数表达式
在 JavaScript 中,函数是一种特殊的值。
function whatIsJsFunc () {
alert('A special value!');
}
alert( whatIsJsFunc );
可以利用这个特性来复制一个函数:
function funcA () {
// ...
}
let funcB = funcA;
甚至可以把函数当作值传入另一个函数: 🔨 示例:
function ifContinue(uid, yes, no) {
// ...
if(condition) {
yes(uid);
} else {
no(uid);
}
}
function yes(uid) {
// ...
}
function no(uid) {
// ...
}
箭头函数
let func = (arg1, arg2, ..., argN) => expression;
也就是:
let func = function(arg1, arg2, ..., argN) {
return expression;
};
箭头函数也可以是多行的:
let func = (arg1, arg2) => {
// ...
}
特性
- 箭头函数没有 this。如果访问 this,则会从外部获取。当我们不想离开当前上下文时,就可以使用箭头函数。
function func() {
const arr = [1, 2, 3];
const showArr = () => {
console.log(this.arr); // this指向外层的arr
}
}
- 箭头函数没有 arguments.
- 箭头函数没有 prototype.