简体   繁体   English

如何在Firefox中使用javascript类?

[英]How do I use javascript classes with Firefox?

How do I code classes in Javascript that will work in Firefox? 如何在Firefox中使用Javascript编写类代码? I am building a media storage website as a project, and, as part of the project, I have created a class that will hold media elements. 我正在将媒体存储网站构建为一个项目,并且作为该项目的一部分,我创建了一个包含媒体元素的类。 The resulting class definition code works fine in Chrome but will not work in Firefox, where it triggers a "class is a reserved identifier" warning. 生成的类定义代码在Chrome中工作正常,但在Firefox中将触发“类为保留标识符”警告,因此无法正常工作。 Some googling confirmed that this is because firefox does not support classes. 一些谷歌搜索确认这是因为firefox不支持类。

How do I fix this? 我该如何解决? I'm guessing there's some workaround and the answer is not to just employ class-less code for Firefox. 我猜测有一些解决方法,答案不只是为Firefox使用无类代码。

Apologies (but also, thank you!) in advance, for what's probably a simple question. 对于可能很简单的问题,请提前致歉(也要感谢您!)。 I am a new programmer. 我是新来的程序员。

Here's the code for the class if helpful: 如果有帮助,请参见以下代码:

class MediaElement {
    constructor(DemographicCategory,GenderCategory,Name,Link,Images,Blurbs,TypeofMedia,Summary,Rating){
        this.Name = Name;
        this.Link = Link;
        this.Image = Images;
        this.Blurbs = Blurbs;
        this.Summary = Summary;
        this.Rating = Rating;
    }
}

Browsers are just catching up with ES6 syntax. 浏览器正赶上ES6语法。 I think Firefox version 45 started to support the class syntax. 我认为Firefox 45版开始支持类语法。

If you want your ES6 code to run on old browsers as well, you have to convert the code into ES5 - called transpiling - using babeljs or Google traceur. 如果您还希望ES6代码也可以在旧的浏览器上运行,则必须使用babeljs或Google traceur将代码转换为ES5(称为转堆)。 Then use it in the front end. 然后在前端使用它。

You can use Babel REPL to see how it would transpile to es5 code (specification full supported by firefox) and use that code on your app, but I highly recommend you to use some transpiler on your code as said by kra3 . 您可以使用Babel REPL来查看如何将其转换为es5代码(firefox支持完整规范)并在您的应用程序上使用该代码,但是我强烈建议您按照kra3的说明在代码上使用一些编译 Babel and google Traceur do a really great work on it BabelGoogle Traceur在此方面做得非常出色

This is how your class will look after the transpilation 这是您的班级在翻译后的样子

 "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var MediaElement = function MediaElement(DemographicCategory, GenderCategory, Name, Link, Images, Blurbs, TypeofMedia, Summary, Rating) { _classCallCheck(this, MediaElement); this.Name = Name; this.Link = Link; this.Image = Images; this.Blurbs = Blurbs; this.Summary = Summary; this.Rating = Rating; }; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM