Skip to content

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

Description

@lin-123

函数 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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions