简体   繁体   English

您如何使用Javascript中的长变量?

[英]How do you work with long variables in Javascript?

How do you recommend to work with long variables in Javascript? 您如何建议在Javascript中使用长变量? Thanks! 谢谢!

For example... 例如...

window.location.hash.substring(2).split("/")[0].something().hello;

object["object"].object(object.hello.how.are.you[another.object(function.inisde())]);

My solutions 我的解决方案

  • Use with() { (...) } 与with(){ (...) }一起使用

如果要多次使用它,请务必将其分配给另一个变量

var simple = object.hello.how.are.you[another.object(function.inisde())];

I find it useful (in any language) to NOT chain method calls together in most cases. 我发现在大多数情况下不要将方法调用链接在一起(用任何一种语言)都是有用的。 The cons to doing this are 这样做的缺点是

1) If there is some sort of null exception, it is difficult to know where it occurs, especially if the code looks like 1)如果存在某种空异常,则很难知道它的发生位置,尤其是代码看起来像

if (a.b.c.d.e || f.g.h.i.k) { ... }

then your NPE like exception could have happened in any of 10 places. 那么您的NPE类似异常可能发生在10个地方中的任何一个地方。 Imagine if the variables are more than 1 letter long. 假设变量的长度超过1个字母。

2) The code is less readable this way. 2)这种方式的代码可读性较差。 The following is infinitely more readable. 以下内容更具可读性。

var b = a.b,
    c = b.c,
    d = c.d,
    e = d.e;
var conditionOne = e.isTrue()

you don't necessarily need to create a var for every level, but you could for levels that make sense. 您不一定需要为每个级别都创建一个变量,但是您可以为有意义的级别创建一个var。

3) Its easier to see what is going on in a debugger if the variables are separated out. 3)如果将变量分开,则更容易查看调试器中发生的情况。

The bottom line is, with some extra typing your code is a lot more readable and a lot more maintainable. 最重要的是,通过进行一些额外的输入,您的代码更具可读性,并且更具可维护性。

If you have to use expressions like 如果您必须使用类似

object["object"].object(object.hello.how.are.you[another.object(function.inisde())]);

it usually means code is badly designed. 这通常意味着代码设计错误。 :) The usual method to make this code comprehensible is to use variables. :)使该代码易于理解的通常方法是使用变量。 It requires more code, but at least it becomes readable. 它需要更多代码,但至少它变得可读。

var anotherObject = another.object(function.inisde())
var hello = object.hello.how.are.you[anotherObject];
object["object"].object(hello);

If the expression is linear, you can easily split it into several lines. 如果表达式是线性的,则可以轻松地将其分成几行。

window.location.hash.substring(2)
    .split("/")[0]
    .something().hello;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM