Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give a second name to a variable in javascript [closed]

I have a code source that contains a long variable name (postCustomThumbnailsScrollerHeight).

I don't want to rename this variable for the whole code source so that I easily continue the project, but to have a shorthand of its name. I tried following solution (which works) at the first declaration of the variable, but I am not sure if it is the correct way to do so. I have a different color of d in IDE:

var postCustomThumbnailsScrollerHeight= d= $('.post-scroller').outerHeight();

I am seeking by this question your usual expert advice.

like image 946
Adib Aroui Avatar asked Jun 15 '15 14:06

Adib Aroui


1 Answers

No, this isn't really correct: you're not declaring the d variable, only assigning to it, and thus

  1. making it global (which may or not be desired)
  2. making your code incompatible with strict mode

Here's a solution:

var d = $('.post-scroller').outerHeight(),
    postCustomThumbnailsScrollerHeight = d;

Note that this should only be done for readability/typing issues, not for downloaded script size: minifiers should be used for that latter goal.

Be also careful that you're not making an alias, but really two variables. If you assign to one, you won't change the other one. It's hard to give a definite advice without more information but the usual solution is to have namespaced object:

Assuming you have a struct

myApp.thumbnailScrollers.postCustom = {height:...

then you would just assign that latter object to a local variable in a module or function:

var s = myApp.thumbnailScrollers.postCustom

In this case, changing s.height would also change myApp.thumbnailScrollers.postCustom.height.

like image 55
Denys Séguret Avatar answered Sep 27 '22 17:09

Denys Séguret