1

I am facing a strange error in node.js express framework.

I created a file say test.js which has the following code

function a(){

}

a.prototype.b = function(){
    this.c("asdsad");
}

a.prototype.c = function(string){
    console.log("ccc"+string)
}

/*var ob = new a();
ob.b();*/

module.exports = a;

and another file call_test.js

var test = require('./test');
var test_ob = new test();
test_ob.b();

when I am running node call_test.js it is giving me correct output cccasdsad

BUT, when I am calling test.js using express middleware in file express_test.js

var express = require("express");
var app = express();
var test = require('./test');
var test_ob = new test();

app.get('/testAPI',test_ob.b);

I am getting error this.c is not a function when I am hitting testAPI.

Can you tell me why this is not working when using in middlewares.

user3110655
  • 121
  • 3
  • 20

1 Answers1

0

The calling context of your app.get line is app, so when the b function tries to run this.c("asdsad");, it's trying to access app.c when you're actually trying to access test_ob.c.

When passing the b function to app.get, bind the b function's this value to the test_ob so it will be referenced properly:

app.get('/testAPI',test_ob.b.bind(test_ob));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320