ES6 js关键字作为参数的确切行为

时间:2019-06-28 07:42:51

标签: javascript node.js ecmascript-6

我有一个预期会返回“未定义”或任何错误的代码,但它给出了输出。

let i = (x, c) => {
    c(x);
};

i(20, (undefined) => {
    let j = undefined;
    console.log(j);
});


function y(undefined) {
    let a = undefined;
    console.log(a);
}
y(90);

如果在函数参数中使用保留字,将如何工作并改变行为?

2 个答案:

答案 0 :(得分:4)

undefined不是保留字。

这是一个全局只读变量。

在狭窄的范围内,没有什么可以阻止您定义另一个具有相同名称的变量。

答案 1 :(得分:3)

undefined不是保留字,如您在此处看到的:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords

在您的情况下,undefined实际上保留了回调值,在第一种情况下为20,在第二种情况下为90。

例如,如果您要将值undefined分配给作用域ja,则可以使用void 0。 有关void的工作方式的更多信息,也可以在这里找到(而且void实际上是javascript中的保留字):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

let i = (x, c) => {
    c(x);
};

i(20, (undefined) => {
    let j = void 0;
    console.log(j);
});


function y(undefined) {
    let a = void 0;
    console.log(a);
}
y(90);