我应该在JavaScript的短块/函数中定义变量吗? [英] Should I define variables in short blocks/functions of JavaScript?

查看:75
本文介绍了我应该在JavaScript的短块/函数中定义变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你有一个大块时,我知道定义变量是有帮助的。但是在变量仅用于一次的短块/函数中,看起来只是浪费了字节。这里有一个示例。这样做不是更好:

I know defining variables is helpful when you have a big block. But in short blocks/functions, where the variable is used once only, it seems just a waste of bytes. Here's an example. Isn't it better to do this:

function SelectInput() {
            document.getElementById("input").select();

而非此:

rather than this:

 function SelectInput () {
            var input = document.getElementById ("input");
            input.select ();
        }


推荐答案

有一个表达式会被不必要地多次评估。你也可以使用变量来提高可读性,通过描述性命名,并将大型链分成合理的块。

You should use a variable whenever there is an expression that would unnecessarily be evaluated multiple times. You also can use variables that increase readability by being named descriptively, and breaking large chains into reasonable chunks.

块的大小无关紧要。

在你的情况下,变量 input 非常没用,很显然 document.getElementById(input )返回一个/输入。

In your case the variable input is pretty useless, it's obvious that document.getElementById("input") returns an/the input.

这篇关于我应该在JavaScript的短块/函数中定义变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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