根据Google JavaScript样式指南在Blocks中的函数声明 [英] Function Declarations Within Blocks according to the Google JavaScript style guide

查看:200
本文介绍了根据Google JavaScript样式指南在Blocks中的函数声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Google JavaScript样式指南,函数声明不应在块中声明,因为它不是ECMAScript的一部分。但是,我并不完全清楚什么算作块。

According to the Google JavaScript style guide, function declarations should not be declared within blocks since this is not a part of ECMAScript. However, I'm not entirely clear on what counts as a block.

具体来说,我有一个构造函数,我想在该构造函数的范围内定义一个函数。这是否算作一个块内的函数,因为它在一组{}内?如果是这样,这是否意味着每个函数声明必须是全局的?

Specifically, I have a constructor function and I want to define a function within the scope of that constructor. Would this count as a function within a block, since it is within a set of {}? If so, does that mean every function declaration must be global?

一些好的衡量代码:

function Constructor() {
    function Shout () { alert('THE BEST UX IS IN ALL CAPS.'); }
}



右(?)



RIGHT (?)

function Constructor() {
    var Shout = function () { alert('THE BEST UX IS IN ALL CAPS.'); };
}


推荐答案

函数不是块。一个块(例如)在之后,,或,如果

A function is not a block. A block is (for example) what follows a while, for, or if.

首先,要了解函数声明( function foo(){} hoisted 到其包含函数范围的顶部(即,您可以通过与声明相同的范围内的任何名称访问声明的函数)。:

First, understand that function declarations (function foo() {}) are hoisted to the top of the scope of their containing function (i.e., you can access a declared functions by name anywhere in the same scope as the declaration).:

foo();
function foo() { }

这个无序代码是100%合法的因为 foo 的声明被提升到 foo()调用之上。但是,现在假设你有条件声明:

This out-of-order code is 100% legal because the declaration of foo is hoisted to above the foo() invocation. However, now imagine you have a conditional declaration:

if(false) {
    function foo() { }
}

从语言设计的角度来看,应该 foo 被悬挂?程序流程永远不会进入程序段,但我们通常会提升所有声明。由于这种混淆,块内的声明不是ECMAScript规范定义的语法的一部分(尽管每个实现都支持这种语法,但在每个实现中会产生不同的非标准效果)。

From a language-design perspective, should foo be hoisted? The program flow will never enter the block, but we customarily hoist all declarations. Due to this confusion, declarations inside blocks are not part of the grammar defined by the ECMAScript spec (though each implementation does support this grammar, but causes a different, nonstandard effect in each).

在另一个函数中使用函数不会产生这种混淆:

Having a function inside another function does not carry this confusion:

function bar() {
    function foo() { }
}

显然 foo 将被提升到栏的顶部(无论何时运行)。

It's obvious that foo will be hoisted to the top of bar (whenever it runs).

因此,你的第一个例子非常好。

Thus, your first example is perfectly fine.

这篇关于根据Google JavaScript样式指南在Blocks中的函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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