3

I've made a Utilities javascript "class" that performs some utility functions.

Instead of having to call Utilities.XYZ, I'd like to be able to do something like #.XYZ.

2 Answers 2

9

# is invalid identifier character in Javascript but you can use something else

var $U = Utilities;

this will make it possible to use $U.XYZ. Since $ is used by many Javascript libraries you can use $U as an alias for Utilities. Easy to understand/remember and short to type. This is aslo more versatile than single sign identifier, because you can define several aliases each for their own longer coutnerpart:

$A, $B, ... $Z
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I ended up going with your solution.
@Darcy: Great! It will get accepted then... (in two days or something) ;)
4

# isn't a legal identifier, but _ and $ are.

var $ = Utilities;

Note that $ is used by several libraries (including but not limited to jQuery, Prototype, and MooTools), and _ is used by underscore.js. And of course you can always add a character or two.

The full list of valid identifier characters is in the specification, but essentially, an identifier may start with $, _, or any alphabetic character; and then subsequent characters may be any of those as well as digits and (in recent versions of JavaScript) accented letters in various languages.

3 Comments

Dang that's what I thought :(. I use jquery so I can't use $....maybe I'll go with underscore. Thanks
@Darcy: Well, you can use $ with jQuery if you really want to: api.jquery.com/jQuery.noConflict You'd just have to either use jQuery everywhere, or come up with your own alias ($j or even $.j if you like).
Thanks for the tip. I went with Robert's suggestion of using $U. This works well because I have a validation class and I can use $V for it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.