上下文:
我正在看书You Don't Know JS: Up & Going, Chapter 2: Into JavaScript 。在Polyfilling部分,作者给出了以下示例:
if (!Number.isNaN) {
Number.isNaN = function isNaN(x) {
return x !== x;
};
}
所以,这里要做的是创建一个polyfill,以便ES6方法Number.isNaN可以在较旧的浏览器(即 ES6 之前的版本)中运行。正如我所料,他使用了较旧的 isNaN方法。前一种方法实际上是有意弃用后者的。
问题:
为什么 isNaN 被用作命名 function expression 的标识符 ?我本来希望它能以某种方式用在 body 中。为什么?由于网络示例中常见的所有标识符,在比较函数表达式与函数声明时采用以下形式:
函数声明:
function foo() {
// ..
}
函数表达式:
var foo = function bar() {
// ..
};
因此,在此示例中,bar 是在“bar()”字符串后面的括号内定义的。那么,当 isNaN 是 JavaScript 中已经定义的函数时,为什么要使用上面的“isNaN”呢?我们实际上是为了填充的目的而重写它吗?我在这里错过/误解了什么?
最佳答案
当表达式中有命名函数时,该值不会提升,而是保存在表达式作用域中。所以原始值没有改变。
示例
function bar(){
console.log("In Bar")
}
var foo = function bar(){
console.log("In Foo")
}
bar();
foo();
为什么要使用它?
如果出现异常,这将有助于您进行调试。匿名函数不会在堆栈跟踪中显示任何名称,如果 1 个函数中有 4-5 个匿名函数,则很难确定哪一个函数失败了。有了命名函数就变得有点简单。
var bar = function Test() {
(function() {
(function() {
(function() {
throw new Error("I have no Name2")
})()
})()
})()
}
var foo = function Test() {
(function inFoo1() {
(function inFoo2() {
(function inFoo3() {
throw new Error("I have no Name2")
})()
})()
})();
}
function init() {
try {
foo();
} catch (ex) {
console.log(ex.stack)
}
try {
bar();
} catch (ex) {
console.log(ex.stack)
}
}
function start() {
init();
}
start();
您还可以引用Why using named function expressions?了解更多信息。
关于javascript - isNaN 可以用作命名函数表达式中的标识符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43983341/