繁体   English   中英

nodejs中的Static变量

[英]Static variable in nodejs

我在 NodeJS 中使用 ES6 样式代码。

尝试创建 static 变量时出现错误。

代码:

'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 = "";
}

错误:

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)

我的错误是什么?

该提案仍处于第二阶段。 到目前为止,如果没有 babel 插件transform-class-properties ,就无法将赋值运算符与 static 关键字一起使用。

如果您不进行编译,则至少需要为 static class 字段使用 Node.js v12.4.0。 https://node.green/#ESNEXT-candidate--stage-3--static-class-fields-public-static-class-fields显示了跨 Node.js 版本支持的功能。

此外,在您的addToCounter function 中,您还需要使用Count.count = Count.count + 1 如果您希望能够在每个实例上存储属性,则需要在方法和属性声明之前删除static关键字。

暂无
暂无

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

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