为什么在 JavaScript 的函数范围内使用 let? [英] Why let at function scope in JavaScript?

查看:43
本文介绍了为什么在 JavaScript 的函数范围内使用 let?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 let 的块与函数作用域 &var(或者我认为我做到了).最近我遇到了一些在函数作用域中使用 let 的 JavaScript,我认为它等同于使用 var,例如:

I understand the block vs. function scoping of let & var (or I thought I did). Recently I ran across some JavaScript that used let in function scope where I thought it would be equivalent to using var, like:

function xyz ( abc ) {
    let mno = abc - 1;   /* or whatever */
    ...
}

那和使用 var 有什么功能上的区别吗?还是只是一种风格?

Is there any functional difference between that and using var there? Or is it just a stylistic thing?

推荐答案

没有任何区别.这要么是风格问题,要么是对 varlet 工作方式的误解.也许原作者(你看到的那个写函数的人)认为 letconst 是一样的(几乎Swift 等语言).换句话说,有时人们将一种语言的样式/语法引入另一种语言,因为声明看起来很相似,但实际上意味着完全不同的东西.

No difference whatsoever. It's either a stylistic thing or a misunderstanding of how var and let work. Perhaps the original author (the person who wrote the function you saw) thought that let is the same as const (which is almost the case in languages like Swift). In other words, sometimes people bring styles/syntax from one language into another because the declarations look similar, but in reality mean completely different things.

我理解 let & 的块和函数作用域var(或者我以为我做了)

I understand the block vs. function scoping of let & var (or I thought I did)

别担心,你会的.let 用于块作用域,正如您指出的那样.

Don't worry, you do. let is for block-scoping, just as you pointed out.

这篇关于为什么在 JavaScript 的函数范围内使用 let?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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