最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to fix SyntaxError: fields are not currently supported error in JavaScript, Firefox? - Stack Overflow

programmeradmin3浏览0评论

I've just been learning JavaScript, and I'm fairly new to coding. I was learning about properties and fields and for some reason Firefox won't run if my class contains fields.

Here's some code that gives the error in the title.

class Animal {
  _paws = true;

  get paws() {
    return _paws;
  }
}

let cat = new Animal();

console.log(cat.paws);

I've just been learning JavaScript, and I'm fairly new to coding. I was learning about properties and fields and for some reason Firefox won't run if my class contains fields.

Here's some code that gives the error in the title.

class Animal {
  _paws = true;

  get paws() {
    return _paws;
  }
}

let cat = new Animal();

console.log(cat.paws);
Share Improve this question asked May 10, 2019 at 19:23 user9642557user9642557 0
Add a comment  | 

2 Answers 2

Reset to default 17

Firstly, there's an error in your code. It should be this._paws in the return statement.

class Animal {
  _paws = true;

  get paws() {
    return this._paws;       // Correct here.
  }
}

let cat = new Animal();

console.log(cat.paws);

Since this answer was posted, Firefox has gained support for public (and private) class field declarations. The Chrome Platform Status documentation on this is out-of-date, as can be seen by the present FIXED status of the Mozilla bug it links to.

The equivalent Mozilla documentation shows support for public field declarations from version 69. By the way, this chart is also partly out-of-date, as in fact Firefox Android has the same level of support as Firefox Desktop.

For production use of this feature you should bear in mind this caveat from the Mozilla documentation:

Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like Babel.

Both developer resource sites cited above indicate that Safari still lacks support for this feature (although given their incompleteness, who can say whether this is still accurate).

Just do this for a quick fix:

class Animal {
  // _paws = true; Remove this line.

  // Initialize your private fields in constructor instead
  constructor() {
    this._paws;
  }

  get paws() {
    return this._paws; // Must use this._fieldName to reference
  }
}

let cat = new Animal();

console.log(cat.paws);

Note that private field is still in the experimental stage on most browsers except Google Chrome.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论