首页 > 解决方案 > JavaScript:类函数中未定义“this”

问题描述

我有一个包含所有快速页面功能的打字稿类,但是当我尝试使用以下方法访问其类的成员变量时出现“未定义”错误this

class CPages {
    private Version: string;

    constructor(version: string) {
        this.Version = version;
        console.log(this.Version); // <- now 'this' refers to the class CPages. Output: 1.0
    }

    public async sendPage(req: express.Request, res: express.Response) {
        console.log(this.Version); // <- now 'this' is undefined and so is this.Version. Output: Cannot read property 'Version' of undefined
        res.render('page', {
            version: this.Version
        });
    }
}

/* ... */

const Pages = new CPages("1.0");

App.get('/', Pages.sendPage);

我看了一下箭头函数的行为(这里),似乎很相似。但与那里的示例不同,我既不能访问主程序,也不能使用this. 那么,如何在不将其作为参数发送的情况下访问版本变量呢?

ps:代码有点简化,App.get(...);本身就在一个类中。

标签: javascriptnode.jstypescriptexpress

解决方案


class CPages {
    constructor(version) {
        this.Version = version;
        // console.log(this.Version);
    }
    async sendPage(){
        console.log('sendPage', this.Version); 
    }
}


let p = new CPages('1.0');
// p.sendPage(); // good

function middle(req, res, next){
  console.log('middleware')
  next()
}

middle(undefined, undefined, p.sendPage) // bad
middle(undefined, undefined, p.sendPage.bind(p)) // good

这工作正常,仅供参考,但您将您的类函数传递为中间件,稍后会...

   function(req, res, next){
      // next is your function
      next() // "this" is now this function
   }

正如其他人建议的那样,您可以使用.bind(Pages)绑定正确的this


推荐阅读