函数定义未提升 [英] function definitions not hoisted

查看:118
本文介绍了函数定义未提升的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

W.r.t吊装fxn定义。

W.r.t Hoisting of fxn definitions.

if (true) {
  function foo() {
    alert(1)
  }
} else {
  function foo() {
    alert(2)
  }
}
foo()

Chrome,大约2-3个月前 - 将打印2.现在,它正在打印1.我错过了什么,或者控制台是否停止了fxn的升级!

Chrome, some 2-3 months ago - would print 2. Now, it's printing 1. Did I miss something or, did console stop hoisting on fxn's!

DEMO - 打印1.我不知道在哪里可以找到旧浏览器版本的演示。可能是老款v8引擎的节点安装?
当前chrome版本 - 49

DEMO -- prints 1. I'm not sure where to find demo of the older browser version. Probably older v8 engine's node installation?. Current chrome version - 49

推荐答案

您所拥有的代码在严格模式下无效。函数不会被块提升(或者至少它们不应该被提升),块内的函数声明在ES6之前是完全非法的。你应该写

The code you have is invalid in strict mode. Functions don't get hoisted out of blocks (or at least they shouldn't), function declarations inside blocks were completely illegal until ES6. You should write

"use strict";
var foo;
if (true) {
  foo = function() {
    alert(1)
  };
} else {
  foo = function() {
    alert(2)
  };
}
foo()

获得可重复且预期的所需行为结果。

to get the desired behaviour with reproducible and expected results.


我是否错过了某些内容,或者控制台是否在fxn上停止提升!

Did I miss something or, did console stop hoisting on fxn's!

看起来V8已更新以符合 ES6规范。它确实将它们提升到函数/ top范围,但仅在实际遇到声明时(在您的情况下,有条件地)。

Looks like V8 was updated to align with the ES6 spec. It does "hoist" them to the function/top scope, but only when the declaration is actually encountered (in your case, conditionally).

这篇关于函数定义未提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆