首页 > 解决方案 > 在另一个静态方法(JavaScript)中调用静态方法时,“this”关键字未定义

问题描述

我正在导出/导入一个空数组以实现 MVC 模式,并且我能够通过调用Mentor类的allMentors方法成功地将数据存储在其中。

其次,我想成为 DRY 并从数组中获取数据,然后用它来寻找特定的导师,但我得到一个空数组。

我搜索了互联网,并按照使用此关键字的示例并在另一个内部调用静态方法,但 NodeJS 抛出一个未定义的错误。

ALL MENTORS 方法

class Mentor{

static async allMentors(req, res) {

        try {

        users.forEach(user => {
            if(user.is_mentor === true) {
                mentors.push(user);
            }
        })

        const ObjKeyRename = (src, map) => {
                const dst = {};

                for (const key in src) {
                    if (key in map)
                        // rename key
                        dst[map[key]] = src[key];
                    else
                        // same key
                        dst[key] = src[key];
                }
                return dst;
        };

        const uniqueMentors = Array.from(new Set(mentors.map(m => m.id)))
                .map(id => {
                   return  new Promise((resolve, reject)=> {
                        const currMentor =  mentors.find(m => m.id === id);
                        const modMentor =  ObjKeyRename(currMentor, { "id": "mentorId" });
                        return resolve(modMentor);
                    })
                }) 

        Promise.all(uniqueMentors).then(output => {
            output.forEach(async obj => {
               await delete obj['password'];
            })

            return res
            .status(200)
            .json(new ResponseHandler(200, 'All Mentors', output, null).result());
        })

        } catch (err) {
            return res
                .status(500)
                .json(new ResponseHandler(500, err.message, null).result());

        }

    }


static async singleMentor(req, res) {

        const returnedMentors = this.allMentors; 
        console.log('THE RETURNED:',returnedMentors)
        const theMentor = returnedMentors.find(u => u.mentorId === parseInt(req.params.mentorId));

        try {
            if (!theMentor) return res
                .status(404)
                .json(new ResponseHandler(404, `Mentor number ${req.params.mentorId} not found`, null).result());

            return res
                .status(200)
                .json(new ResponseHandler(200, 'Your mentor', theMentor, null).result());

        } catch (err) {
            return res
                .status(500)
                .json(new ResponseHandler(500, err.message, null).result())
        }

    }
}

export default Mentor;

我究竟做错了什么?感谢您作为 JS 学习者的持续帮助。

标签: javascript

解决方案


您的代码存在多个问题:

  • 静态方法需要由 Class( Mentor) 而不是 Reference( this)调用
  • 需要等待或使用回调(.then())调用异步方法

因此,例如,您有课程MentorHandler

class Mentor {
  constructor() {
  }

  static async singleMentor(req, res) {

    // ... some more code
  }

  static async allMentors(req, res) {
    // await the result of the method
    // call by class
    const returnedMentors = await Mentor.allMentors(); 


    // ... some more code
  }
}

推荐阅读