0

我们如何在 es6 类中访问 koa js 路由context(this)和 es6this类?

当我尝试使用this.name未定义访问类属性时

测试.js

export default class {
  constructor (opts) {
    this.name = 'test'
  }

  welcome () {
    console.log(this.name) // 'this' is UNDEFINED. Trying to access class property. But getting undefined
    this.body = 'welcome '+this.params.name // 'this' works fine here as a koa reference
  }
}

应用程序.js

import test from './test'
let Test = new test({})

router.get('/test/:name', Test.welcome)
4

1 回答 1

-1

我不确定您使用的类声明和导出语法,我认为这可能是问题所在。

像这样的东西应该可以工作(请注意,此代码适用于 require 但它应该与 相同import):

测试.js

class test{
    constructor(opts) {
        this.name = 'test';
    }

    welcome() {
        console.log(this.name); // 'this' is UNDEFINED. Trying to access class property. But getting undefined
        this.body = 'welcome ' + this.params.name; // 'this' works fine here as a koa reference
    }
}

module.exports = test;

应用程序.js

let test = require('./test');
let Test = new test({});

Test.welcome();

虽然这段代码显示this.name得很好,但它会中断this.params,我假设你已经在其他地方声明了。

于 2016-10-18T22:58:03.320 回答