45

I'm taking a look at the angular 1.2 source code, and I'm just curious why some functions are prefixed with the two dollar signs. Is this some sort of convention?

4

2 回答 2

58
  • Single $ for reserved, public identifiers
  • Double $$ for reserved private identifiers

To quote the docs:

$ Prefix Naming Convention

...

If you inspect a Scope, you may also notice some properties that begin with $$. These properties are considered private, and should not be accessed or modified.

于 2013-10-12T19:51:25.987 回答
6

If I may add:

Angularjs Docs

Other than just being significant to Angularjs, the '$$' or '$' are just characters that are allowed in variable names. Angularjs uses both to identify significance for you and their own development team.

You could name all of your variables in the same way; but to avoid naming collisions, stay away from this practice. Here are some examples if you did...

$$$$myVariableName; $myVariableName$; _myVariableName_; $$$$$$myVariableName$$$$$$$$

Here is a link to test out JS variable names if you wish:

Variable Name Validator

Here is a link to MDN as well that explains allowed characters:

MDN allowed characters link

and here is the text:

Variables

You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.

Some examples of legal names are Number_hits, temp99, and _name.

Angulajs includes quite a bit of information in each object; some of the items are for Angularjs, and some are for the developer, which means that some may not be editable, but all should be available for reference if that is what you were going to use it for.

However, in future releases any private identifiers may disappear as the Angularjs team expects the developer not to use the reserved / private names.

In the case of the posted 'similar link' here is what Angularjs says:

$ Prefix Naming Convention You can create your own services, and in fact we will do exactly that in step 11. As a naming convention, Angular's built-in services, Scope methods and a few other Angular APIs have a $ prefix in front of the name.

The $ prefix is there to namespace Angular-provided services. To prevent collisions it's best to avoid naming your services and models anything that begins with a $.

If you inspect a Scope, you may also notice some properties that begin with $$. These properties are considered private, and should not be accessed or modified.

于 2015-01-13T17:56:13.357 回答