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.
答案 0 :(得分:13)
No, this isn't really correct: you're not declaring the d
variable, only assigning to it, and thus
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
.
答案 1 :(得分:0)
Probably you have different color because in this case b
it's global variable.
As for my opinion will be better to write all definitions on different lines:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;
答案 2 :(得分:0)
尽管JavaScript本身不支持引用,但您可以使用以下代码来激发它们:
function d(){
return postCustomThumbnailsScrollerHeight;
}
然后到处使用d()
。它不是很优雅,但据我所知,它是获取JavaScript引用的唯一方法。
答案 3 :(得分:-2)
Do you have a problem declaring that var in the next line? You could just do:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;