Javascript keyword rewriting

I know that delete is a keyword in JavaScript. So I have this code (for example):

 var user = { create : function () { // Create a user account }, delete : function () { // Delete a user account } }; 

The above works (banning older versions of IE), so my question is a good idea. Obviously, calling user.delete(); much clearer for someone using code than something like user.delete_one();

Obviously, keywords are important, but in each case is it normal (if I don't need legacy IE support) to use this method or is there a better solution?

+6
source share
4 answers

The code will work as expected because you are not rewriting the JS keyword. If you try to declare a keyword as the name of a variable or function, JS will display a SyntaxError: Unexpected token delete error.

This is good as you choose, but don't override JS keywords directly.

+3
source

You can do it as follows:

 var user = { create : function () { // Create a user account }, 'delete' : function () { // Delete a user account } }; 

Or using double quotes "

+8
source

Do not try to overwrite keywords. IMO is bad practice and will be very confusing for another developer. Instead of having a remove function, you can simply rename it to remove

+3
source

When you use an object literal , then the property name can be any of the following:

IDName
String Literal
Numeric Literal

StringLiteral and NumericLiteral should be clear. What is an IdentifierName ?

Let's look at section 7.6 of the specification :

Identifier:

IdentifierStart
IdentifierName * IdentifierPart *

IdentifierStart ::
UnicodeLetter
$
_
\ UnicodeEscapeSequence

IdentifierPart ::
IdentifierStart
UnicodeCombiningMark
UnicodeDigit
UnicodeConnectorPunctuation
<ZWNJ>
<ZWJ>

So, IdentifierName really is any sequence of characters, as described above. Is the reserved word unimportant.

The names that you can use for variable and function names are called Identifier and are defined as:

Identifier::
IdentifierName, but not ReservedWord

You see that reserved words are explicitly excluded as opportunities for identifiers, but not for object properties.

However , you never know how a "good" parser is, and whether it follows all the rules. In addition, linting tools like JSHint usually warn you about using a reserved keyword, even though it is valid. To be safe, you must put such words in quotation marks and even use anchor notation to access it:

 var foo = {'delete': ... } foo['delete'] = ....; 

If this is too cumbersome, just do not use the reserved word as the name of the property. For example, instead of delete you can use remove .

+2
source

Source: https://habr.com/ru/post/927462/


All Articles