JavaScript中的全局函数的'let','const'和'var' [英] 'let', 'const', and 'var' on global functions in JavaScript

查看:133
本文介绍了JavaScript中的全局函数的'let','const'和'var'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当定义全局函数时,应该使用 var let const

When defining a global function, should I use var, let, or const?

var fn = function () {};
let fn = function () {};
const fn = function () {};

我在这里主要考虑C / Pascal意义上的全局函数,即一个函数可用/可见,在当前文件的其余部分。

I'm here thinking primarily of global functions in the C/Pascal sense, i.e. a function that is available/visible, by name, in the rest of the current file.

当我学习JavaScript时,我们使用 var fn = .. functino fn().. ,我正在尝试更新我的知识,因为浏览器现在支持ECMAScript 6本机。

When I was learning JavaScript we used either var fn=.. or functino fn ().., and I'm trying to update my knowledge since browsers are now supporting ECMAScript 6 natively.

推荐答案

简而言之:我建议您使用 const 。为什么?

In short: I would recommend you to use const. Why?

(在以下示例中,假设我们在浏览器环境中。)

它们被悬挂并成为全局对象的属性。

They are hoisted and become properties of the global object.

fn(); // No error
function fn() {}
console.log('fn' in window); // true



函数表达式与 var / h2>

它们没有被提升,但是在全局范围内声明的变量总是成为全局对象的属性。

Function expressions with var

They are not hoisted, but a variable declared in the global scope always becomes a property of the global object.

fn(); // TypeError
var fn = function () {};
console.log('fn' in window); // true



函数表达式与 let / h2>

它们没有悬停,它们不会成为全局对象的属性,而是可以为变量分配另一个值。由于JavaScript是松散类型的,所以您的函数可以被一个字符串,数字或其他任何东西替代。

Function expressions with let

They are not hoisted, they do not become properties of the global object, but you can assign another value to your variable. Since JavaScript is loosely typed, your function could be replaced by a string, a number, or anything else.

fn(); // ReferenceError
let fn = () => {};
console.log('fn' in window); // false
fn = 'Foo'; // No error



具有 const的函数表达式



它们没有被提升,它们不会成为全局对象的属性,因此无法通过重新分配进行更改。确实,一个常数不能被重新声明。

Function expressions with const

They are not hoisted, they do not become properties of the global object and you cannot change them through re-assignment. Indeed, a constant cannot be redeclared.

fn(); // ReferenceError
const fn = () => {};
console.log('fn' in window); // false
fn = 'Foo'; // TypeError

这篇关于JavaScript中的全局函数的'let','const'和'var'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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