“this”引用在nodeJs中不起作用

"this" reference is not working in nodeJs

本文关键字:nodeJs 不起作用 引用 this      更新时间:2023-09-26

我的nodeJs代码中有两个方法,例如

function method1(id,callback){
  var data = method2();
  callback(null,data);
}
function method2(){
  return xxx;
}
module.exports.method1 = method1;
module.exports.method2 = method2;

为了使用 SinonMocha 测试函数方法1,我必须stub方法 方法2。 为此,它需要调用方法 method2 作为

function method1(id,callback){
      var data = this.method2();
      callback(null,data);
}

为此测试代码

describe('test method method2', function (id) {
    var id = 10;
    it('Should xxxx xxxx ',sinon.test(function(done){
       var stubmethod2 = this.stub(filex,"method2").returns(data);
       filex.method1(id,function(err,response){
         done();
       })
    })
})

使用此测试用例通过,但代码停止工作,错误 this.method2 不是一个函数。

有什么方法可以摆脱thismodule.exports似乎有问题。

如果我错过了任何其他信息,请告诉我。

您没有正确使用 module.exports。

将代码更改为:

export function method1(id,callback){
  var data = method2();
  callback(null,data);
}
export function method2(){
  return xxx;
}

然后:

const MyFuncs = require('path_to_file_with_methods');

在需要方法的地方,像这样调用:

MyFuncs.method1(){} MyFuncs.method2(){}

模块导出的文档

您还可以通过以下方式使用 module.exports。

module.exports = {
    method1: method1,
    method2: method2
}

并以同样的方式要求。

编辑:

请注意,如果您的版本支持它,您还可以在导出中加入一些语法糖:

module.exports = {
    method1,
    method2
}

这适用于一般的对象文字表示法。

使用箭头函数来更正此方法

在您的情况下

function method1(id,callback){
  var data = this.method2();
  callback(null,data);
}

可以更改为

  let method1 = (id,callback)=>{
    var data = this.method2();
    callback(null,data);
  }