Javascript private class fields or methods not working in iOS Chrome or Safari

Viewed 1190

Do Javascript private fields or methods using # work in iOS?

For example, I have this class:

Class A { 
    #privateFunction() {return ""} 
}

Creating an instance of class A works in Android and desktop. But in iOS, I get the following error: cannot find variable: A

I know the error is related to iOS, because if I made the privateFunction public, it works.

I'm testing the code on a real iPhone device updated to the latest iOS version.

Update: I updated iOS to 14.5.1 but nothing changed.

3 Answers

JS Private Field is supported in Safari & Chrome IOS 14.5 (released 10 days ago).

Safari & Chrome in IOS must be updated to 14.5 for the Class Private fields to work

Click the link below for more information in browser compatibilities,

https://caniuse.com/?search=private%20field

On iOS, even Chrome uses Apple's JavaScriptCore JavaScript engine instead of its usual V8 (and uses the WebKit rendering engine, instead of the usual Blink) because of Apple policies¹ (this is true of all other browsers as well).

JavaScriptCore only just added support for private fields in iOS 14.5, so you'll need to be on a completely up-to-date device (as of this writing). The proposal is no longer "in progress," it's in the specification (as of the last TC39 meeting).


¹ They can't use their own JavaScript engines because that would require allocating executable memory, which Apple only allows Apple apps to do. (V8 did add an interpreter-only mode, but JavaScriptCore is quite a good JavaScript engine and the iOS Chrome folks just use it instead.) They can't use their own rendering engines because Apple doesn't want them to, you have to use their WebView component instead.

What you wrote there, i.e. #privateFunction(), is a private method, not a private field.

Private methods are unsupported in Safari older than version 15

At the time of writing, this is the browser support in MDN according to the Private class features page:

enter image description here

Because private class methods are not supported by any existing Safari version, it didn't work for you on iOS 14.5.1 either.

Since iOS devices remain very popular, my advice at this time would be to avoid using most (if not all) of these features listed above until such time in the future when browser compatibility improves.

The good news is that Safari 15 on iOS 15 and macOS 12 supports private class methods and accessors, according to the official release notes.

Related