Overwriting Javascript Keywords

梦想与她 提交于 2019-12-23 09:03:41

问题


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 (barring older versions of IE), so my question is - is it a good idea. Obviously the call user.delete(); is much clearer to someone utilizing the code than something like user.delete_one();

Obviously keywords are important, but on a case by case basis is it alright (granted I don't need legacy IE support) to use this method, or is there a better solution?


回答1:


You code will work as expected, because you are not overwriting JS keyword. If you try to declare a keyword as variable or function name, JS will show error SyntaxError: Unexpected token delete.

It 's alright with the way you choose but don't override JS keywords directly.




回答2:


You can do it like this:

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

   'delete' : function () {
       // Delete a user account
   }
};

Or by using double quotes "




回答3:


Don't attempt to overwrite keywords. IMO this is bad practice and would be very confusing for another developer. Rather than having a delete function you can simply rename it to remove




回答4:


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

IdentifierName
StringLiteral
NumericLiteral

StringLiteral and NumericLiteral should be clear. What exactly is a IdentifierName?

Lets have a look at section 7.6 of the specification:

IdentifierName ::
     IdentifierStart
     IdentifierName *IdentifierPart*

IdentifierStart ::
     UnicodeLetter
     $
     _
     \ UnicodeEscapeSequence

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

So, an IdentifierName really is any character sequence as described above. Whether is a reserved word does not matter.

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

Identifier ::
     IdentifierName but not ReservedWord

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

However, you never know how "good" a parser is and if it adheres to all rules. Additionally, linting tools such as JSHint will usually warn you of the use of a reserved keyword, despite the fact that it is valid. To be on the safe side, you should put such words in quotes and even use bracket notation to access it:

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

If this is too cumbersome, just don't use a reserved word as property name. For example, instead of delete, you could use remove.



来源:https://stackoverflow.com/questions/12840610/overwriting-javascript-keywords

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!