Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在 JavaScript 中定义函数的14种方法 #297

Open
Sogrey opened this issue Sep 17, 2020 · 0 comments
Open

在 JavaScript 中定义函数的14种方法 #297

Sogrey opened this issue Sep 17, 2020 · 0 comments

Comments

@Sogrey
Copy link
Owner

Sogrey commented Sep 17, 2020

  1. 声明函数
function sum(a, b) { return a + b; } 
  1. 表达式函数
// 可以命名:
(function sum(a, b) { return a + b; });

// 也可匿名 (AVOID):
(function(a, b) { return a + b; });

// 也能分配给变量:
const sum = function sum(a, b) { return a + b; })
  1. 箭头函数
// 一般形式:
(a, b) => { return a + b };

// 单参数,一行返回:
name => name.split(' ')

// 多参数,一行返回:
(a, b) => a + b

// 单参数,带函数体
name => { return name.split(' '); }
  1. 生成器函数
function *sum(a, b) { yield a + b; }
  1. 异步函数
async function sum(a, b) { return await a + b; }
  1. 构造函数(AVOID)
new Function(‘a’, ‘b’, ‘return a + b;);
  1. 导出函数
// 默认导出
export default function(a, b) { return a + b; };

// 命名导出
export function sum(a, b) { return a + b; };
  1. 对象属性函数
// 一般形式:
const object = {
  sum: function(a, b) { return a + b; },
};

// 简写:
const object = {
  sum(a, b) { return a + b; },
};
  1. 对象动态属性函数
const functionName = "sum";
const object = {
  [functionName]: function(a, b) { return a + b; },
};
  1. 对象属性的 Getter/Setter 函数
// 一般形式:
const object = {
  get answer { return 42; },
  set answer(value) { /* 一些操作value的代码 */ },
};

//  使用 defineProperty
const obj = {};
Object.defineProperty(obj, "answer", {
  get() { return 42; },
  set(value) { /* 一些操作value的代码 */ },
});
  1. 对象动态属性的 Getter/Setter 函数
const functionName = "answer";
const object = {
  get [functionName]() { return 42; },
  set [functionName](value) { /* 一些操作value的代码 */ },
};
  1. 类方法函数
class Compute {
  // 一般形式:
  sum(a, b) { return a + b; }
}

class Compute {
  // 静态:
  static sum(a, b) { return a + b; };
}
  1. 类属性函数
class Compute {
  // 一般形式:
  sum = function (a, b) { return a + b; };
}class Compute {
  // 静态:
  static sum = function(a, b) { return a + b; };
}
  1. 类私有函数
class Compute {
  // 一般形式:
  #sum(a, b) {
    return a + b;
  }  // 静态:
  static #sum(a, b) {
    return a + b;
  }
}

选自 https://mp.weixin.qq.com/s/qGvaesdpfaI3gr6cp2vNHg

@Sogrey Sogrey added this to javascript in Web面经题 Sep 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Web面经题
javascript
Development

No branches or pull requests

1 participant