使用函数之外的东西的函数和自包含的函数叫什么?

What do you call function that use stuff outside of the function and function that is self contained?

这两个函数有名称或术语吗?我确定他们会搜索,但不知道要搜索什么。

// edit: thanks to Bergi: 
// this is a function with `no free variables` (outer variables)

function add (a, b) { return a + b }

// edit: thanks to Bergi: 
// this is a function with `free variables` (b) if you didn't know that

var b = 2
function add (a) { return a + b }

如果一个函数超出了它自己的范围,它是否被称为特殊的东西?不使用其自身范围之外的任何功能的函数是什么?


我想向某人解释的是,如果我在哪里编写这个导出两个辅助函数的实用程序文件

// util
function divide (a, b) {
  return a / b
}

function half (a) {
  return divide(a, 2)
}

export {
  divide,
  half
}

然后在另一个文件中我将只使用除法函数

import { divide } from util

然后 WebPack/rollup 将能够摇树并丢弃最终包中的 half 函数

但是如果从实用程序文件中导入 half 函数的位置

import { half } from util

但是我的主脚本中并不真的需要 divide 函数,无论如何我最终都会在我的包中同时拥有这两个函数,因为 half 取决于 divide

如果我将函数更改为不使用其自身范围之外的任何变量,如下所示:

function half (a) {
  return a / 2
}

那么它将 "dependency" 免费。

Is it called something special if a function goes outside of its own scope?

我们称它们为 closures. It has a free variable,在 JS 中是在作用域中按词法查找的。

然而,虽然 在 JavaScript 中,这可能不是您想要使用的术语;大多数人将它与动态创建的函数相关联,这对于模块级函数来说很奇怪。

What do you call the function that don't use anything outside of its own scope?

没有自由变量的函数”将适合。