JS 中的 Symbol 是什么?

ES 6 引入了一个新的数据类型 Symbol,它是用来做什么的呢?
为了说明 Symbol 的作用,我们先来描述一个使用场景。

我们在做一个游戏程序,用户需要选择角色的种族。

var race = {
  protoss: 'protoss', // 神族
  terran: 'terran', // 人族
  zerg: 'zerg' // 虫族
}

function createRole(type){
  if(type === race.protoss){创建神族角色}
  else if(type === race.terran){创建人族角色}
  else if(type === race.zerg){创建虫族角色}
}

那么用户选择种族后,就需要调用 createRole 来创建角色:

// 传入字符串
createRole('zerg') 
// 或者传入变量
createRole(race.zerg)

一般传入字符串被认为是不好的做法,所以使用 createRole(race.zerg) 的更多。

如果使用 createRole(race.zerg),那么聪明的读者会发现一个问题:race.protoss、race.terran、race.zerg 的值为多少并不重要。

改为如下写法,对 createRole(race.zerg) 毫无影响:

var race = {
  protoss: 'askdjaslkfjas;lfkjas;flkj', // 神族
  terran: ';lkfalksjfl;askjfsfal;skfj', // 人族
  zerg: 'qwieqwoirqwoiruoiwqoisrqwroiu' // 虫族
}

也就是说:

race.zerg 的值是多少无所谓,只要它的值跟 race.protoss 和 race.terran 的值不一样就行。

Symbol 的用途就是如此:Symbol 可以创建一个独一无二的值(但并不是字符串)。

用 Symbol 来改写上面的 race:

var race = {
  protoss: Symbol(),
  terran: Symbol(),
  zerg: Symbol()
}

race.protoss !== race.terran // true
race.protoss !== race.zerg // true
你也可以给每个 Symbol 起一个名字:

var race = {
  protoss: Symbol('protoss'),
  terran: Symbol('terran'),
  zerg: Symbol('zerg')
}

不过这个名字跟 Symbol 的值并没有关系,你可以认为这个名字就是个注释。如下代码可以证明 Symbol 的名字与值无关:

var a1 = Symbol('a')
var a2 = Symbol('a')
a1 !== a2 // true

如果你觉得我说得还是太复杂了,看不懂,你可以记一句话:

Symbol 生成一个全局唯一的值。

以上,就是 Symbol 的简述,更详细更权威的知识参考下面的自学链接。

自学链接:

MDN: Symbol – JavaScript

阮一峰:ECMAScript 6入门

作者:方应杭

29 thoughts on “JS 中的 Symbol 是什么?”

  1. Thanks for some other great post. Where else may
    anybody get that kind of information in such an ideal
    way of writing? I have a presentation next week, and I
    am at the search for such info.

  2. I simply couldn’t go away your website prior to suggesting that I actually loved the standard information an individual supply on your guests?
    Is gonna be again regularly to investigate cross-check new posts

  3. I just like the helpful info you provide in your
    articles. I’ll bookmark your weblog and test again here frequently.
    I’m slightly certain I will learn a lot of new stuff proper right here!
    Good luck for the following!

  4. Oh my goodness! Incredible article dude! Thank you so much,
    However I am having troubles with your RSS.
    I don’t understand the reason why I am unable to join it.
    Is there anybody having the same RSS problems? Anybody
    who knows the answer can you kindly respond? Thanx!!

  5. Magnificent beat ! I wish to apprentice at the same time as
    you amend your website, how can i subscribe for a weblog site?
    The account aided me a appropriate deal. I were tiny bit acquainted of this your broadcast provided vivid transparent concept

  6. Hey! Someone in my Facebook group shared this site with us so I came to look it over.

    I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers!
    Excellent blog and amazing design.

  7. Excellent site. A lot of useful info here. I’m sending it to several buddies ans also sharing in delicious. And of course, thank you for your sweat!

  8. I had this article saved some time before but my computer crashed. I have since gotten a new one and it took me a while to locate this! I also really like the template though.

  9. After I initially commented I appear to have clicked on the -Notify me when new comments
    are added- checkbox and from now on whenever a comment is added I get 4 emails with the same comment.
    There has to be a way you are able to remove me from that service?
    Cheers!

  10. I precisely had to thank you so much yet again. I do not know the things I would’ve gone through without the entire points revealed by you concerning such a topic. Entirely was a real distressing crisis for me, however , noticing the professional strategy you treated it forced me to weep over happiness. Extremely happier for the information and in addition sincerely hope you know what an amazing job you’re accomplishing teaching the rest with the aid of your site. I am certain you haven’t met all of us.

  11. Thanks so much for providing individuals with an extremely special opportunity to read articles and blog posts from this website. It’s usually very kind and full of a great time for me and my office co-workers to visit your blog at least three times per week to find out the latest issues you have got. And lastly, I’m just always astounded with all the astounding guidelines served by you. Some 4 tips in this posting are honestly the very best we have all had.

  12. I wish to show my affection for your kind-heartedness in support of persons who must have assistance with this particular topic. Your personal dedication to passing the message around had become rather good and have surely enabled regular people much like me to realize their pursuits. Your valuable guideline means a whole lot to me and still more to my office workers. Thank you; from all of us.

  13. I simply wanted to jot down a brief remark to say thanks to you for those great secrets you are showing on this site. My time intensive internet lookup has now been compensated with good quality facts and strategies to share with my pals. I would suppose that many of us readers are definitely lucky to exist in a fabulous network with so many special professionals with beneficial points. I feel very much fortunate to have come across the webpages and look forward to some more exciting minutes reading here. Thank you once more for everything.

  14. Good way of describing, and fastidious post to get facts about my presentation topic,
    which i am going to present in university. cheap flights 2CSYEon

  15. I wanted to draft you a very small word to finally say thanks as before considering the great techniques you have discussed on this site. This has been shockingly generous of you to deliver openly what exactly many of us could have supplied as an e-book to get some money on their own, mostly seeing that you might well have tried it in case you desired. The techniques additionally served to provide a easy way to fully grasp many people have the identical interest the same as my very own to know great deal more pertaining to this issue. Certainly there are millions of more pleasurable times in the future for individuals who look into your site.

  16. My husband and i were joyful when Michael managed to conclude his investigations from the ideas he had out of the weblog. It’s not at all simplistic just to be releasing thoughts which people today may have been selling. And we also fully understand we have the blog owner to thank for this. The explanations you’ve made, the simple website menu, the friendships you help create – it’s got all spectacular, and it’s helping our son in addition to the family feel that the theme is enjoyable, and that is especially vital. Many thanks for the whole lot!

  17. Just want to say your article is as astounding. The clearness for your
    post is simply cool and i can think you are an expert on this subject.
    Well with your permission allow me to seize your feed to stay up to date with forthcoming post.
    Thank you one million and please keep up the enjoyable work.

  18. I intended to post you the little bit of note to help say thank you once again regarding the great solutions you have documented on this page. It has been really seriously open-handed with you to allow unhampered all numerous people could possibly have offered for an e-book to help with making some dough for their own end, and in particular considering that you might have tried it in the event you decided. Those solutions likewise acted as a great way to know that some people have the identical desire much like my personal own to understand more and more when considering this condition. I am certain there are many more fun instances in the future for those who check out your blog.

  19. I want to show some thanks to you for bailing me out of this particular scenario. Just after researching through the the web and finding views which are not pleasant, I believed my life was over. Being alive devoid of the answers to the problems you have fixed by way of this short post is a critical case, as well as those that could have adversely damaged my career if I had not encountered the blog. Your personal understanding and kindness in handling everything was important. I am not sure what I would have done if I had not come upon such a stuff like this. I am able to at this time look forward to my future. Thank you very much for your reliable and effective help. I won’t think twice to recommend your blog post to any individual who should receive support about this matter.

  20. Once I initially commented I clicked the -Notify me when new feedback are added- checkbox and now every time a remark is added I get 4 emails with the same comment. Is there any method you’ll be able to take away me from that service? Thanks!

  21. Remarkable issues here. I’m very glad to see your article.
    Thank you so much and I am looking forward to contact you.
    Will you kindly drop me a e-mail?

  22. Oh my goodness! an incredible article dude. Thanks However I am experiencing concern with ur rss . Don抰 know why Unable to subscribe to it. Is there anybody getting an identical rss drawback? Anybody who knows kindly respond. Thnkx

发表评论

电子邮件地址不会被公开。