最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

object literal - How is "first-name" a reserved word in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

Note: This question pertains to the book 'JavaScript: The Good Parts' written by Doug Crockford. As I was reading a chapter on Objects, I came across a statement as follows:

The quotes around a property's name in an object literal are optional if the name would be a legal JavaScript name and not a reserved word. So quotes are required around "first-name", but are optional around "first_name".

And the following is the example of an object literal provided in the book:

var stooge = {
    "first-name": "Jerome",
    "last-name": "Howard"
};

Now, I might have misinterpreted the text here but to me it seems like Mr. Crockford is saying first-name (with the hyphen) IS a reserved word whereas first_name (with the underscore) is not. If that is the case, I don't understand how the former can be a reserved word. I found no other explanation in the book why this is. Can someone please explain?

Note: This question pertains to the book 'JavaScript: The Good Parts' written by Doug Crockford. As I was reading a chapter on Objects, I came across a statement as follows:

The quotes around a property's name in an object literal are optional if the name would be a legal JavaScript name and not a reserved word. So quotes are required around "first-name", but are optional around "first_name".

And the following is the example of an object literal provided in the book:

var stooge = {
    "first-name": "Jerome",
    "last-name": "Howard"
};

Now, I might have misinterpreted the text here but to me it seems like Mr. Crockford is saying first-name (with the hyphen) IS a reserved word whereas first_name (with the underscore) is not. If that is the case, I don't understand how the former can be a reserved word. I found no other explanation in the book why this is. Can someone please explain?

Share Improve this question asked Sep 17, 2013 at 16:04 BinaryCatBinaryCat 1,3002 gold badges17 silver badges32 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

It is not a reserved word. Without the quotes, javascript will interpret the - character as a subtraction operator, attempt to perform the operation, and fail.

One reason for this is that javascript prefers to ignore whitespace whenever it can. Thus 2 - 3 is the same as 2-3.

Putting the whole thing in quotes causes the js to interpret as just another character, not an operator.

发布评论

评论列表(0)

  1. 暂无评论