Home >Web Front-end >JS Tutorial >Several ways to define functions in JS
Do you know how many ways there are to create a function in JavaScript? The following article will introduce you to several different methods of defining functions in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
1. Declaration function
function sum(a, b) { return a + b; }
2. Expression function
// 可以命名: (function sum(a, b) { return a + b; }); // 也可匿名 (AVOID): (function(a, b) { return a + b; }); // 也能分配给变量: const sum = function sum(a, b) { return a + b; })
3. Arrow function
// 一般形式: (a, b) => { return a + b }; // 单参数,一行返回: name => name.split(' ') // 多参数,一行返回: (a, b) => a + b // 单参数,带函数体 name => { return name.split(' '); }
4. Generator function
function *sum(a, b) { yield a + b; }
5. Asynchronous function
async function sum(a, b) { return await a + b; }
6. Constructor (AVOID)
new Function(‘a’, ‘b’, ‘return a + b;’);
7. Export function
// 默认导出 export default function(a, b) { return a + b; }; // 命名导出 export function sum(a, b) { return a + b; };
// 一般形式: const object = { sum: function(a, b) { return a + b; }, }; // 简写: const object = { sum(a, b) { return a + b; }, };
9. Object dynamic property function
const functionName = "sum"; const object = { [functionName]: function(a, b) { return a + b; }, };
10. Object property Getter/Setter function
// 一般形式: const object = { get answer { return 42; }, set answer(value) { /* 一些操作value的代码 */ }, }; // 使用 defineProperty const obj = {}; Object.defineProperty(obj, "answer", { get() { return 42; }, set(value) { /* 一些操作value的代码 */ }, });
11. Getter/Setter functions of object dynamic properties
const functionName = "answer"; const object = { get [functionName]() { return 42; }, set [functionName](value) { /* 一些操作value的代码 */ }, };
12. Class method functions
class Compute { // 一般形式: sum(a, b) { return a + b; } } class Compute { // 静态: static sum(a, b) { return a + b; }; }
13. Class attribute function
class Compute { // 一般形式: sum = function (a, b) { return a + b; }; }class Compute { // 静态: static sum = function(a, b) { return a + b; }; }
14. Class private function
class Compute { // 一般形式: #sum(a, b) { return a + b; } // 静态: static #sum(a, b) { return a + b; } }
If you combine some of these methods, there are even more possibilities. Do you know of any other methods? Please leave a message and tell me.
Related free learning recommendations: js video tutorial
The above is the detailed content of Several ways to define functions in JS. For more information, please follow other related articles on the PHP Chinese website!