What is the hash tag used for in JavaScript?
I'm not talking about in the URL. I know what that 开发者_C百科does. I'm talking about how it's used in actual code.
After trying to assign it as a variable, I realized that it's reserved, but I don't know what for.
Javascript, or more precisely ECMAscript, is an evolving language. Some symbols and keywords (such as "class") have been reserved for future versions, even though they may not have any meaning at the moment.
I dont think, that this sign is somehow reserved fot another functionality. I found that rule here:
You must not use any punctuation marks of any kind in a JavaScript variable name, other than the underscore; for example... some:thing or big# or do'to would all be illegal.
This ist just, that javascript does not accept punctation signs in variable names ant due to this not parsing variables named like this as variables.
See here: What characters are valid for JavaScript variable names?
An ongoing proposal (currently in stage 4) utilizes hashtags to mark fields as private. It is part of the ES2022 standard.
Example:
class Foo {
x = 1; // public field
#y = 2; // private field
add() {
return this.x + this.#y;
}
}
In JavaScript variable names, no punctuation marks are permitted except for the underscore (_) and dollar sign ($). You can't start a variable name with a number, but otherwise all letters and numbers are permitted in a variable name.
So you can't have a variable name with #
in it, no less a variable named #
. It has no special meaning, it's just not permitted just as variable can't be named ~
.
精彩评论