未提升的函数定义
function definitions not hoisted
W.r.t 提升 fxn 定义。
if (true) {
function foo() {
alert(1)
}
} else {
function foo() {
alert(2)
}
}
foo()
Chrome,大约 2-3 个月前 - 会打印 2。现在,它正在打印 1。我是不是错过了什么,或者控制台是否停止了 fxn 的提升!
DEMO -- 输出 1。我不确定在哪里可以找到旧版浏览器的演示。可能是较旧的 v8 引擎的节点安装?
当前 chrome 版本 - 49
您应该避免使用条件创建的函数。
例如,假设以下代码:
if (false){
function foo(){
console.log(1)
}
}
foo()
Firefox 不会提升该功能,这将导致 ReferenceError: foo is not defined
。然而,Chrome 仍然提升函数并打印 1
。很明显,您 处理不同的浏览器行为。因此,根本不要做那样的事情(如果你真的想的话,也可以使用函数表达式)。
另见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
Functions can be conditionally declared, that is, a function statement can be nested within an if statement. Most browsers other than Mozilla will treat such conditional declarations as an unconditional declaration and create the function whether the condition is true or not, see this article for an overview. Therefore they should not be used, for conditional creation use function expressions.
特别是查看链接的文章,它在一定程度上解释了您遇到的问题。所以 Chrome 似乎在这方面有所改变。但同样,不要使用有条件创建的函数。
请注意,正如 FREEZE 评论的那样,您应该使用 'use strict';
,它不允许这样的代码,而是会抛出异常。
您的代码在严格模式下无效。函数不会被提升到块之外(或者至少他们不应该),块内的函数声明在 ES6 之前是完全非法的。你应该写
"use strict";
var foo;
if (true) {
foo = function() {
alert(1)
};
} else {
foo = function() {
alert(2)
};
}
foo()
获得具有可重现和预期结果的预期行为。
Did I miss something or, did console stop hoisting on fxn's!
看起来 V8 已更新以与 保持一致。它 "hoist" 它们到 function/top 范围,但仅当实际遇到声明时(在您的情况下,有条件地)。
W.r.t 提升 fxn 定义。
if (true) {
function foo() {
alert(1)
}
} else {
function foo() {
alert(2)
}
}
foo()
Chrome,大约 2-3 个月前 - 会打印 2。现在,它正在打印 1。我是不是错过了什么,或者控制台是否停止了 fxn 的提升!
DEMO -- 输出 1。我不确定在哪里可以找到旧版浏览器的演示。可能是较旧的 v8 引擎的节点安装? 当前 chrome 版本 - 49
您应该避免使用条件创建的函数。
例如,假设以下代码:
if (false){
function foo(){
console.log(1)
}
}
foo()
Firefox 不会提升该功能,这将导致 ReferenceError: foo is not defined
。然而,Chrome 仍然提升函数并打印 1
。很明显,您 处理不同的浏览器行为。因此,根本不要做那样的事情(如果你真的想的话,也可以使用函数表达式)。
另见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
Functions can be conditionally declared, that is, a function statement can be nested within an if statement. Most browsers other than Mozilla will treat such conditional declarations as an unconditional declaration and create the function whether the condition is true or not, see this article for an overview. Therefore they should not be used, for conditional creation use function expressions.
特别是查看链接的文章,它在一定程度上解释了您遇到的问题。所以 Chrome 似乎在这方面有所改变。但同样,不要使用有条件创建的函数。
请注意,正如 FREEZE 评论的那样,您应该使用 'use strict';
,它不允许这样的代码,而是会抛出异常。
您的代码在严格模式下无效。函数不会被提升到块之外(或者至少他们不应该),块内的函数声明在 ES6 之前是完全非法的。你应该写
"use strict";
var foo;
if (true) {
foo = function() {
alert(1)
};
} else {
foo = function() {
alert(2)
};
}
foo()
获得具有可重现和预期结果的预期行为。
Did I miss something or, did console stop hoisting on fxn's!
看起来 V8 已更新以与