【问题标题】:JavaScript: "this" undefined in function of class [duplicate]JavaScript:类函数中未定义“this”[重复]
【发布时间】:2021-07-21 19:23:23
【问题描述】:

我有一个 typescript 类,其中包含我所有的快速页面函数,但是当我尝试使用 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);

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

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

【问题讨论】:

  • 当您执行.get() 绑定时,您的方法正在丢失其上下文。你可以使用App.get('/', Pages.sendPage.bind(Pages)) 来解决这个问题。

标签: javascript node.js typescript express


【解决方案1】:

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

【讨论】:

  • 非常感谢,.bind(Pages) 成功了。
【解决方案2】:

当你这样做App.get('/', Pages.sendPage); 时,这意味着你正在发送一个要在/ 路由上使用的函数。此时,它不再绑定到您的 Pages 对象。它像这样在全局上下文中运行:

let obj = {
'val' : 1,
'func1' : function(){
console.log(this.val);
}
}
obj.func1(); //Works fine
let newRef = obj1.func;
newRef(); //Error

您可以使用bind() 返回一个修改后的函数,其中this 值绑定到Pages 对象。

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

【讨论】:

    猜你喜欢
    • 2017-03-02
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2022-01-10
    • 2011-04-30
    • 2013-06-26
    相关资源
    最近更新 更多