Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make alias in javascript

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.

like image 858
Darcy Avatar asked Apr 21 '26 11:04

Darcy


2 Answers

# 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
like image 78
Robert Koritnik Avatar answered Apr 22 '26 23:04

Robert Koritnik


# 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.

like image 34
T.J. Crowder Avatar answered Apr 23 '26 00:04

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!