javascript - "arguments"应该在标识符的保留字列表中吗?

标签 javascript typescript

The lists保留关键字不包括“参数”。他们应该吗?我不明白如何将“参数”用作标识符。

最佳答案

有几个类似关键字的东西(甚至是实际关键字)在 JavaScript(以及 TypeScript)中不是保留字; details here . arguments 不是关键字,它是传统函数(使用 function 关键字的函数)和方法(使用方法语法在类或对象字面量)。这意味着您可以隐藏它,在尚未拥有它的上下文中声明它,等等。

I don't see how "arguments" could be used as an identifier.

可以,但仅限于松散模式。以下是一些示例:

// Arguments isn't implicitly declared outside traditional
// functions and methods
const arguments = 1;
console.log(arguments);     // 1
try {
    arguments = 1.5;
} catch (e) {
    console.log(e.message); // "Assignment to constant variable." (or similar)
}

const fn = () => {
    // Arrow functions don't have an `arguments` identifier declared for them
    let arguments = 2;
    console.log(arguments); // 2
};

fn();

function fn2() {
    if (true) {
        // Shadows the function-wide `arguments` only within this block
        let arguments = 3;
        console.log(arguments); // 3
    }
    // This uses the implicit `arguments` for the function
    console.log(arguments.length); // 0
}

fn2();

这在严格模式下是无效的,在严格模式下对arguments(和eval)的使用有限制。从上面的链接:

The names arguments and eval are not keywords, but they are subject to some restrictions in strict mode code. See 12.1.1, 12.1.3, 14.1.2, 14.4.1, 14.5.1, and 14.7.1.

这些不同的链接部分放在一起,基本上意味着 arguments(和 eval)不能用作标识符。

其他不是保留字的关键字或类似关键字的东西:

  • letconst 只是标识符之前的关键字。
  • async 只是 function 或方法声明之前的关键字。否则,它是一个可接受的标识符。
  • await 只是 async 函数中的一个关键字。它是严格模式下的保留字,但在松散模式下不是,其他几个也是。
  • yield 只是生成器函数中的一个关键字。也以严格模式保留。
  • NaNundefinedInfinity 等是全局对象的只读属性,不是关键字。
  • importexport 只是模块中的关键字。

我确定该列表不完整。 :-)

这是保持近 100% 向后兼容性的不断发展、扩展的语言的本质。

关于javascript - "arguments"应该在标识符的保留字列表中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58952313/

相关文章:

javascript - Javascript中这两种编写函数的风格有什么区别

javascript - 转义 "/"在 IE9 中不起作用

typescript - 类型 'DocumentData' 不可分配给类型 'IProduct'

reactjs - 从生产中的标签中删除 JSX 数据属性

javascript - typescript 中的前置条件检查

javascript - 使用 MySQL 填充 jQuery DataTable

javascript - 有没有办法确定浏览器是否可以处理电话链接

javascript - 将 2014 年 3 月 25 日的日期格式设置为数字

angular - 尝试将服务注入(inject) Angular 组件时出错 "EXCEPTION: Can' t 解析组件的所有参数”,为什么?

typescript - 无法从过滤类型中删除带有 never 的属性以获取剩余的键