【问题标题】:How to write proper private method in JavaScript class with Babel?如何使用 Babel 在 JavaScript 类中编写正确的私有方法?
【发布时间】:2019-11-29 06:21:12
【问题描述】:

我在 Apollo 服务器上做 GraphQL 教程。现在我正在尝试从这部分添加批处理 - https://www.apollographql.com/docs/apollo-server/features/data-sources/#batching

我知道我可以在 TypeScript 中使用 private。但不知道如何在 JS 中使用。

据我搜索,我安装了两个 babel 插件,class-propertiesprivate-methods

// .babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ],
  "plugins": [
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    ["@babel/plugin-proposal-private-methods", { "loose": true }],
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-proposal-async-generator-functions"
  ]
}

代码如下:

// datasource.js

import DataLoader from 'dataloader';

class PostAPI extends DataSource {
  constructor({ knex }) {
    super();
    this.knex = knex;
  }

  initialize(config) {
    this.context = config.context;
  }

  // ERROR HERE!
  #postLoader = new DataLoader(ids =>
    this.knex('posts')
      .whereIn('id', ids)
      .select()
      .then(rows => ids.map(id => rows.find(x => x.id === id)))
  );

  async findAll() {
    const posts = await this.knex('posts').select();

    if (!posts.length) return [];
    console.log(posts);
    return posts;
  }

  async findOne({ id: idArg } = {}) {
    /*
    const post = await this.knex('posts')
      .where('id', idArg)
      .first();
    */

    const post = await this.postLoader.load(idArg);

    if (!post) return;
    return post;
  }
}

当我查询单个帖子(findOne)时它会出错:

{
  "errors": [
    {
      "message": "Cannot read property 'load' of undefined",
    }
  ]
}

此外,eslint 警告 # 是“无效字符”。

这是我的.eslintrc

// .eslintrc.json

{
  "root": true,
  "parser": "babel-eslint",
  "parserOptions": {
    "sourceType": "module",
    "ecmaVersion": 2018,
    "allowImportExportEverywhere": false,
    "ecmaFeatures": {
      "globalReturn": false
    }
  },
  "plugins": ["babel"],
  "extends": ["eslint:recommended", "prettier"],
  "env": {
    "browser": true,
    "node": true,
    "es6": true,
    "jest": true
  },
  "rules": {},
  "globals": {}
}

请帮忙。

【问题讨论】:

    标签: javascript node.js graphql babeljs


    【解决方案1】:

    # 是字段名称的一部分。所以你需要在任何你使用它的地方使用#

    const post = await this.#postLoader.load(idArg);
    // ---------------------^
    

    这是一个使用私有字段(也是私有方法)的简单示例:

    class Example {
        #foo = 42;
    
        publicMethod() {
            console.log("From publicMethod:", this.#foo);
            this.#privateMethod();
        }
    
        #privateMethod() {
            console.log("From #privateMethod:", this.#foo);
        }
    }
    
    const e = new Example();
    console.log(e.publicMethod());
    

    Live on Babel's REPL.


    此外,eslint 警告 # 是“无效字符”。

    Private fields 仍然只是第 3 阶段的提案,尚未标准化。 ESLint 似乎没有支持它们的选项。

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2012-02-19
      • 1970-01-01
      • 2021-09-22
      相关资源
      最近更新 更多