在JavaScript类中正确声明静态变量 [英] Correctly declare static variables in JavaScript classes

查看:107
本文介绍了在JavaScript类中正确声明静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我执行以下操作(非常简化):

In my code, I do the following (very simplified):

class AddOrSelectAddress {
    static body; // <-- Error

    static async open() {
        await $.get(basePath + 'Manage/AddOrSelectAddress', null, result => {
            this.body = document.createElement('div');
            this.body.innerHTML = result;
        });
        // ...
    }

    static someOtherMethod() {
        // do something with body
    }
}

我的代码在Chrome中运行良好。但是,Firefox抱怨第二行代码中的错误:

My code works fine in Chrome. Firefox, though, complaints an error in the second line of code:


SyntaxError:错误的方法定义

SyntaxError: bad method definition

我对基于类的JavaScript编程比较陌生。我在这里做什么错了?

I'm relatively new to class-based JavaScript programming. What am I doing wrong here?

静态变量使用JavaScript 并没有真正帮助我,因为它主要使用旧语法。

Static variables in JavaScript doesn't really help me, because it mainly uses old syntax.

推荐答案

静态类字段是第3阶段的提案,表示它们还不是JavaScript语言的正式组成部分。 (第4阶段是最后阶段。)您可以在此处和提案流程此处

Static class fields are a stage 3 proposal, meaning they're not yet an official part of the JavaScript language. (Stage 4 is the final stage.) You can read more about the proposal here and the proposal process here.

当前,Chrome(自72版起)是支持的唯一浏览器静态类字段。

Currently, Chrome (as of version 72) is the only browser that supports static class fields.

要在其他浏览器中使用此功能,您需要使用 Babel rel = nofollow noreferrer> @ babel / plugin- proposal-class-properties 来转换您的代码。但是,如果您还没有使用Babel,那么这可能会过大。

To use this feature in other browsers you would need to use Babel with @babel/plugin-proposal-class-properties to transpile your code. If you're not already using Babel, however, this might be overkill.

或者,您可以在初始化类后将其分配给该类。这在语义上是不相同的,但是适用于您(以及实际上的大多数)用例。

Alternatively, you can assign a property to the class after initializing it. This isn't semantically identical, but works for your (and, indeed, most) use cases.

class AddOrSelectAddress {
  // ...
}

AddOrSelectAddress.body = 'some initial value';

您可以在下面的代码段中看到此功能。

You can see this working in the below snippet.

class AddOrSelectAddress {
  static changeBody(val) {
    this.body = val;
  }

  static someMethod() {
    console.log('in someMethod body is', this.body);
  }

  static someOtherMethod() {
    console.log('in someOtherMethod body is', this.body);
  }
}
AddOrSelectAddress.body = 'some initial value';

AddOrSelectAddress.someMethod();
AddOrSelectAddress.changeBody('some other value');
AddOrSelectAddress.someOtherMethod();

如果您不想为 body 设置初始值,则可以可以省略该行(由于访问对象的不存在属性返回 undefined ),或者您可以将其显式设置为 undefined

If you don't want to set an initial value for body then you could just omit the line (since accessing a nonexistent property of an object returns undefined), or you could explicitly set it to undefined.

这篇关于在JavaScript类中正确声明静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆