Got this code, that works perfectly in all browsers but not in Safari (Version 11.1.2).
class Account {
accountFields = ['field1', 'field2', 'field3']
}
Getting the following error in Safari debugger:
Unexpected token '='. Expected an opening '(' before a method's parameter list
So I tried to add ()
everywhere, around the array, before, after, etc. Nothing works.
You're using an experimental feature known as public field declarations which is currently in stage 3. The only Safari versions that support this feature are v14.1 (released April 26th, 2021) and higher. If you need to support older versions of Safari / a wider variety of browsers you'll need to follow one of the suggestions below.
Instead of using public field declarations, you can use a constructor() method to define the properties for your class instances. Using a constructor does have good browser compatibility (for IE support you can use a constructor function):
class Account {
constructor() {
this.accountFields = ['field1', 'field2', 'field3'];
}
}
As pointed out in the comments by @Baz, you can also use Babel as an alternative solution. Using babel means that you won't have to change your code, which can make things easier on you if you're using public field declarations a lot throughout your project. Babel will transpile/compile your modern JS code into older (ES5 and below) JS code which can be understood by many browsers. You can use this babel plugin like so.
First, install the babel plugin:
npm install --save-dev @babel/plugin-proposal-class-properties
Then add the plugin to your configuration file:
{
"plugins": ["@babel/plugin-proposal-class-properties"]
}
For other installation options (babel CLI, etc), see the usage section of the plugin's docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With