How to make alias in javascript
I've made a Utilities javascript "class" that performs some utility 开发者_如何学Gofunctions.
Instead of having to call Utilities.XYZ
, I'd like to be able to do something like #.XYZ
.
#
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
#
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.
精彩评论