Bản dịch này chưa hoàn thành. Xin hãy giúp dịch bài viết này từ tiếng Anh
Các tham số của hàm mặc định cho phép khởi tạo với các giá trị mặc định khi không truyền giá trị vào đó.
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.
Cú pháp
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
statements
}
Mô tả
Trong JavaScript, tham số của hàm mặc định . Tuy nhiên, chúng thường hữu ích hơn khi tạo giá trị mặc định khác. undefined
Trước đây, quy tắc chung khi tạo giá trị mặc định là kiểm tra các giá trị tham số trong thân hàm và gán vào tham số nếu nó không xác định.
Trong ví dụ sau, nếu không cung cấp giá trị cho b khi gọi hàm multiply, b sẽ không xác định trong phép tính a * b và hàm multiply sẽ trả về NaN.
function multiply(a, b) {
return a * b;
}
multiply(5, 2); // 10
multiply(5); // NaN !
Để tránh điều này, ta sẽ dùng một dòng code xác định b=1 nếu hàm chỉ được gọi với 1 đối số.
function multiply(a, b) {
b = (typeof b !== 'undefined') ? b : 1;
return a * b;
}
multiply(5, 2); // 10
multiply(5); // 5
Với các tham số mặc định trong ES2015, việc kiểm tra thân hàm không còn cần thiết. Bạn có thể gán 1 cho b ở đầu hàm:
function multiply(a, b = 1) {
return a * b;
}
multiply(5, 2); // 10
multiply(5); // 5
Ví dụ
Truyền giá trị undefined với giá trị ảo
Trong lời gọi thứ hai, ngay cả khi đối số thứ nhất không xác định (không phải null hay giá trị ảo), đối số num vẫn mặc định.
function test(num = 1) { console.log(typeof num); } test(); // 'number' (num is set to 1) test(undefined); // 'number' (num is set to 1 too) // test with other falsy values: test(''); // 'string' (num is set to '') test(null); // 'object' (num is set to null)
Xét tại thời điểm gọi
Đối số mặc định được xét tại thời điểm gọi. Trong khi Python, một đối tượng mới được tạo ra mỗi khi hàm được gọi.
function append(value, array = []) { array.push(value); return array; } append(1); //[1] append(2); //[2], not [1, 2]
Áp dụng cho cả hàm và biến:
function callSomething(thing = something()) {
return thing;
}
let numberOfTimesCalled = 0;
function something() {
numberOfTimesCalled += 1;
return numberOfTimesCalled;
}
callSomething(); // 1
callSomething(); // 2
Các tham số mặc định có sẵn cho các tham số mặc định sau:
Các tham số được xác định trước (bên trái) có sẵn cho các tham số mặc định sau:
function greet(name, greeting, message = greeting + ' ' + name) { return [name, greeting, message]; } greet('David', 'Hi'); // ["David", "Hi", "Hi David"] greet('David', 'Hi', 'Happy Birthday!'); // ["David", "Hi", "Happy Birthday!"]
This functionality can be aChức năng này sử dụng cho nhiều trường hợp xảy ra:
function go() {
return ':P';
}
function withDefaults(a, b = 5, c = b, d = go(), e = this,
f = arguments, g = this.value) {
return [a, b, c, d, e, f, g];
}
function withoutDefaults(a, b, c, d, e, f, g) {
switch (arguments.length) {
case 0:
a;
case 1:
b = 5;
case 2:
c = b;
case 3:
d = go();
case 4:
e = this;
case 5:
f = arguments;
case 6:
g = this.value;
default:
}
return [a, b, c, d, e, f, g];
}
withDefaults.call({value: '=^_^='});
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
withoutDefaults.call({value: '=^_^='});
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
Định nghĩa hàm trong thân hàm
Giới thiệu trong Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30). Các hàm được khai báo trong thân hàm không thể được tham chiếu bên trong với các tham số mặc định của hàm ngoài. Nếu bạn thử, ReferenceError sẽ bị loại bỏ. Các tham số mặc định luôn được thực thi trước, hàm khai báo bên trong thân hàm sẽ thực thi sau.
// Doesn't work! Throws ReferenceError.
function f(a = go()) {
function go() { return ':P'; }
}
Tham số không mặc định
Trước Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2), đoạn code sau cho kết quả SyntaxError. Sau đó được sửa lại bug 777060. Các tham số vẫn xuất hiện từ trái qua phải, ghi đè lên các tham số mặc định kể cả các tham số sau không mặc định.
function f(x = 1, y) {
return [x, y];
}
f(); // [1, undefined]
f(2); // [2, undefined]
Tham số bị hủy gán với giá trị mặc định
Có thể dùng giá trị mặc định với kí hiệu destructuring assignment:
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
return x + y + z;
}
f(); // 6
Đặc điểm
| Đặc điểm | Trạng thái | Ghi chú |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Function Definitions' in that specification. |
Standard | Định nghĩa ban đầu |
| ECMAScript (ECMA-262) The definition of 'Function Definitions' in that specification. |
Living Standard |
Trình duyệt tương thích
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Default parameters | Chrome Full support 49 | Edge Full support 14 | Firefox Full support 15 | IE No support No | Opera Full support 36 | Safari Full support 10 | WebView Android Full support 49 | Chrome Android Full support 49 | Firefox Android Full support 15 | Opera Android Full support 36 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
| Destructured parameter with default value assignment | Chrome Full support 49 | Edge Full support 14 | Firefox Full support 41 | IE No support No | Opera Full support 36 | Safari Full support 10 | WebView Android Full support 49 | Chrome Android Full support 49 | Firefox Android Full support 41 | Opera Android Full support 36 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support Yes |
| Parameters without defaults after default parameters | Chrome Full support 49 | Edge Full support 14 | Firefox Full support 26 | IE No support No | Opera Full support 36 | Safari Full support 10 | WebView Android Full support 49 | Chrome Android Full support 49 | Firefox Android Full support 26 | Opera Android Full support 36 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support Yes |
Legend
- Full support
- Full support
- No support
- No support