JavaScript 中的字面值指的是直接寫在程式碼中的固定值,例如數字、字串、陣列與物件。函數則可以透過宣告、表達式或建構式來定義。
3.14
1001
123e5
'John Doe'
'Hello'
[40, 100, 1, 5]
{ firstName: 'John', lastName: 'Doe' }
function myFunction(a, b) {
return a * b;
}
函數宣告會被提升,因此可以在宣告之前呼叫。
const x = function (a, b) {
return a * b;
};
console.log(x(4, 3));
函數表達式通常不會像函數宣告那樣被提升。
若在函數表達式後加上括號,可以建立立即執行函數:
(function () {
console.log('Hello!');
})();
JavaScript 函數具有屬性與方法,例如 arguments.length 與 toString()。
function myFunction(a, b) {
return arguments.length;
}
console.log(myFunction.toString());