简体   繁体   English

nodejs中的Static变量

[英]Static variable in nodejs

I am using ES6 style code within NodeJS.我在 NodeJS 中使用 ES6 样式代码。

When trying to create a static variable I get an error.尝试创建 static 变量时出现错误。

Code:代码:

'use strict';

module.exports =  class Count {
    static addToCounter() {
        //this.count = this.count + 1 || 1;
        this.count = this.count + 1;
        console.log(`count: `+this.count);
    }
    static count = "";
}

Error:错误:

static count = "";
                 ^

SyntaxError: Unexpected token =
    at new Script (vm.js:74:7)
    at createScript (vm.js:246:10)
    at Object.runInThisContext (vm.js:298:10)
    at Module._compile (internal/modules/cjs/loader.js:646:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
    at Module.load (internal/modules/cjs/loader.js:589:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
    at Function.Module._load (internal/modules/cjs/loader.js:520:3)
    at Module.require (internal/modules/cjs/loader.js:626:17)
    at require (internal/modules/cjs/helpers.js:20:18)

What is my mistake?我的错误是什么?

This proposal is still in stage-2.该提案仍处于第二阶段。 As of now, without the babel plugin transform-class-properties , it is not possible to use the assignment operator along with the static keyword.到目前为止,如果没有 babel 插件transform-class-properties ,就无法将赋值运算符与 static 关键字一起使用。

If you are not transpiling, you will need to be using at least Node.js v12.4.0 for static class fields.如果您不进行编译,则至少需要为 static class 字段使用 Node.js v12.4.0。 https://node.green/#ESNEXT-candidate--stage-3--static-class-fields-public-static-class-fields shows supported features across Node.js versions. https://node.green/#ESNEXT-candidate--stage-3--static-class-fields-public-static-class-fields显示了跨 Node.js 版本支持的功能。

Also, inside your addToCounter function, you would also need to use Count.count = Count.count + 1 .此外,在您的addToCounter function 中,您还需要使用Count.count = Count.count + 1 If you want to be able to store properties on each instance, then you would need to remove the static keywords before both the method and the property declaration.如果您希望能够在每个实例上存储属性,则需要在方法和属性声明之前删除static关键字。

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

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