第 11 屆 iT 邦幫忙鐵人賽

DAY 24
Modern Web

從Stack Overflow學前端系列 第 24

從StackOverflow上學CODING(24)為何 ◎ܫ◎或 ☺不能成為一個 JS變數名

Why aren't ◎ܫ◎ and ☺ valid JavaScript variable names?

I noticed that in Internet Explorer (but, unfortunately, not in the other browsers I tested), you can use some Unicode variable names. This made my day, and I was absolutely delighted that I could write fun Unicode-laden code like this:


var ктоείναι草泥马 = "You dirty horse.",
    happy☺n☺mat☺p☺eia = ":)Yay!",
    ಠ_ಠ = "emoticon";

alert(ктоείναι草泥马 + happy☺n☺mat☺p☺eia + ಠ_ಠ);

For some reason, though, ◎ܫ◎, ♨_♨ and ☺ are not valid variable names.

Why do ಠ_ಠ and 草泥马 work, but ◎ܫ◎, ♨_♨ and ☺ don't?

EDIT: Test it out in your browser on JSFiddle. I've tested it in Internet Explorer 9, Chrome, Firefox, and Opera. So far, it seems to only work in Internet Explorer 9. (I don't know about Internet Explorer 8 and below.) Let me know if it works in another browser.

但是出於某些原因,◎ܫ◎, ♨♨ 和 ☺則不是有效的變數名,這是為甚麼呢?

ಠ_ಠ and 草泥马 only contain "letters" used in actual alphabets; that is, ಠ is a symbol from the Kannada alphabet, and 草泥马 consists of Chinese characters.
ಠ_ಠ 和 草泥马 只是"字體"存在於在字母表內,ಠ是一個在Kannada字母表,而草泥马則存在於中文字體中

◎ and ☺, however, are purely symbols; they are not associated with any alphabet.
然而, ◎ 和 ☺ 則是純粹的符號,他們跟任何字母表都沒有關連

The ECMAScript standard, chapter 7.6 (which all the browsers except Internet Explorer are following), states that an identifier must start with one of the following.

a Unicode letter
$ or _
\ followed by a unicode escape sequence.

一個 Unicode字體
$或 _

The following characters of an identifier must be one of the following.
any of the characters permitted at the start:

a Unicode combining mark
a Unicode digit
a Unicode connector punctuation
a zero-width-non-joiner
a zero-width joiner

IE goes beyond the standard and is permissive enough to allow some symbols, such as ☺.
IE則超越了標準、更加寬容的允許更多符號像是 ☺

There’s a tool that will tell you if any string that you enter is a valid JavaScript variable name according to ECMAScript 5.1 and Unicode 6.1.
有一個工具可以告訴你你的字串能不能設為一個 JavaScript變數名根據 ECMAScript 5.1 和 Unicode 6.1

從StackOverflow上學CODING(23) 如何用 JS刪除所有 CSS Class
從StackOverflow上學CODING(25) 甚麼時候用 call()& apply()& bind()
從Stack Overflow學前端30