Can't use “let” keyword in Safari Javascript?

2019-04-25 02:37发布

问题:

I don't understand the best way to use "let" keyword...

  • In IE11 and Chrome45 I can use it fine
  • In Safari8.0.4, like in older versions of Chrome, it gives the error "unexpected use of reserved word 'let'"
  • In Firefox the let keyword only works inside <script type="application/javascript;version=1.7"/>, but this script type isn't even recognized as Javascript in IE11, Chrome45, Safari8.

Here's a JSFiddle that shows it in action: https://jsfiddle.net/p6cgtyg6/1/

So -- I don't mind requiring users to use modern versions of their browsers.

And I don't mind excluding Safari if there honestly is no version of Safari that supports this keyword. (Is that really true? Why does everyone spend all their time griping about IE when Safari seems so much worse in ES6 terms? Have I missed something?).

But how should I allow "let" to work in Firefox while not preventing Chrome/IE? (I haven't yet found links from people griping about how Firefox script tag behaves differently from Chrome, and I'd have expected more complaints, so I figure I must have missed something obvious...)

回答1:

Concerning Safari 8, it's just not supported ; for that browser, I'd recommend using Babel.

If you have the gut feeling that this bug won't be fixed anytime soon* then you could have a script that detect Firefox which would then inject your script(s) with the appropriate value for the type attribute.

As a side note, I would advise not to use let blocks—unless you wanna use this transpiler—nor let expressions which will be dropped.

* fixed in Firefox 44



回答2:

let is a part of ECMAScript 6 specification, and ECMAScript 6 itself is in 'draft' status. Even in its incomplete form its features aren't supported fully by actual browser versions.

Since you want to dive into ES6 today for production, your best bet is to use ES6 to ES5 transpiler, most prominent ones are Babel and Traceur, which are available as both CLI and packages for the build system of your choice. There are online tools for Babel and Traceur to try them out. And Scratch JS extension for Chrome uses both Babel and Traceur and is excellent for developing and compiling ES6 scripts if the build system is not an option.

Here is up-to-date comparison table that embraces ES6 feature support in both browsers and ES6 compilers.

And here is a great collection of ES6-related tools.



回答3:

See browser compatability of this ES6 keyword.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Browser_compatibility

Also see this SO post for ES6 feature detection.