Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  153] [ 4]  / answers: 1 / hits: 15892  / 4 Years ago, sun, february 2, 2020, 12:00:00

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.


More From » safari

 Answers
36

You're using a relatively new feature known as public field declarations. It's currently supported by most modern browsers. However, 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 older 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.


[#51256] Wednesday, January 22, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamilab

Total Points: 687
Total Questions: 88
Total Answers: 86

Location: Antigua and Barbuda
Member since Sat, Apr 24, 2021
3 Years ago
jamilab questions
;