【问题标题】:How do I access parent methods inside this ES5 class?如何访问这个 ES5 类中的父方法?
【发布时间】:2019-01-27 02:08:14
【问题描述】:

我在 NodeJS 中有一个 Babel ES5 类设置,例如:

import fs from "fs";

// Services
import { aws } from "../../services/aws";

class UserController {
    update(req, res, next) {
        const { user } = req.body;

        if (user) {
            req.user = Object.assign(req.user, user);

            req.user.save((err, updatedUser) => {
                if (err) {
                    return res.status(422).json(err);
                }

                return res.json({ user: updatedUser });
            });
        } else {
            return res.sendStatus(400);
        }
    }

    testMethod() {
        this.update();
    }
}

module.exports = new UserController();

如何从另一个父方法中访问“更新”方法?在这种情况下很难看出“this”是如何定义的

【问题讨论】:

  • 这取决于 testMethod 的使用方式。这是 ES6,不是 ES5。

标签: node.js babeljs ecmascript-5


【解决方案1】:

当您在 JavaScript 中的 class 中创建方法时,this 指的是类本身的实例。因此,您可以通过其中的任何方法访问class 上的所有定义。

类实际上只是带有语法糖的函数。Check here for a thorough explanation of how classes work,包括this的用法。

您可以使用构造函数为类定义变量,如下所示:

class MyClass {
  constructor(name) {
    // setting a value on "this", which refers to the class object
    this.name = name;
  }

  printName() {
    // logging "this.name" which we set in the constructor
    console.log(this.name);
  }
}

const myObject = new MyClass("Michael");
myObject.printName(); // prints out "Michael"

看看this在构造函数和类方法中是如何工作的?

这些类方法实际上只是定义从构造函数分配给this 的函数的简写。

使用您的示例,实际发生的情况如下:

class UserController {
  constructor() {
    this.update = function(req, res, next) {
      const { user } = req.body;

      if (user) {
          req.user = Object.assign(req.user, user);

          req.user.save((err, updatedUser) => {
              if (err) {
                  return res.status(422).json(err);
              }

              return res.json({ user: updatedUser });
          });
      } else {
          return res.sendStatus(400);
      }
    }

    this.testMethod = function() {
      this.update();
    }
  }
}

【讨论】:

  • 'this'不是指'class',它指的是'class'的'instance'。
  • 谢谢@StevenSpungin,我修正了我的答案。
【解决方案2】:

testMethod 中使用this 会起作用。

如果您想确保调用由模块导出的单例,您可以持有一个实例并调用它。

当然,如果您创建另一个实例,这种方法就会失败。 在你的情况下,你还没有导出你的类,所以无论如何都没有客户端能够创建它。

const userController = new UserController()

// class definition here...

// In your class definition, use `userController` instead of `this`.
// For example

testMethod() {
    userController.update()
}

module.exports = userController;

【讨论】:

  • 好点。我认为他要求解释“this”如何在一个类中工作以访问同一类的其他方法,但我不确定;这个问题并不完全清楚。
  • 使用这种方法的好处是你可以从内部类,甚至从其他类,或者根本没有类中明确地调用它。
  • 正确我在方法中询问 this 的上下文。我发现这种方法更清洁
猜你喜欢
  • 2011-07-01
  • 1970-01-01
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 2015-07-28
相关资源
最近更新 更多