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

函数命名及书写不规范范例 #26

Open
lin-123 opened this issue Mar 30, 2024 · 2 comments
Open

函数命名及书写不规范范例 #26

lin-123 opened this issue Mar 30, 2024 · 2 comments

Comments

@lin-123
Copy link
Owner

lin-123 commented Mar 30, 2024

函数 7.1

1. 使用 function foo() {} 形式,导致作用域提升,会出现在函数被声明之前就可以使用

// 函数调用出现在函数定义之前,当代码行数比较多时,定位函数比较不方便,不利于从上到下阅读代码的习惯
doSomething();

function doSomething() {
    // ...
}


// 推荐如下形式
const doSomething = function() {
    // ...
};
doSomething(); 

1. 推荐使用命名函数,而不是匿名函数,在函数体报错时方便追踪

// doSomething.js
// 报错信息只会定位到这个文件, 不会提示名称
export default () => {
  console.log('匿名函数');
  throw new Error('匿名函数');
}

// main.js
import doSomething from './doSomething';

doSomething();
image
// 命名函数报错
export default function namedFunction() {
  console.log('命名函数');
  throw new Error('命名函数');
}
image
@Seansun1314
Copy link

Seansun1314 commented Mar 30, 2024 via email

@lin-123
Copy link
Owner Author

lin-123 commented Mar 31, 2024

简写的函数式组件也经常会出现这种问题, 如

import { useEffect } from "react"

export default () => {
  useEffect(() => {
    throw new Error('some error');
  }, []);
  return <div>
  </div>
}

会导致

  1. 报错信息无法定位到是哪个组件
image
  1. vscode 中代码提示、代码索引不生效

推荐写法

// better 简洁一些
export function SomeComponent() {
  useEffect(() => {
    throw new Error('some error');
  }, []);
  return <div></div>;
}

// best
const SomeComponent = () => {
  useEffect(() => {
    throw new Error('some error');
  }, []);
  return <div></div>;
}
export default SomeComponent;

命名函数在报错提示里会提示函数名称, 方便搜索
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants