0

I am new to Javascript, so pardon me my trivial mistakes. I have written the following script in which res is supposed to be a Global variable in the script file. I am setting the global res in a method and then accessing it in another method, however the issue is, this.issue returns undefined in method Y but it isn't undefined in the method X where I assign a value to it. Why is that?

Method X is called before Method Y.

var res;

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express', shortenedUrl: ''});
});


router.X('/yolo', jsonParser, function(req, res, next) {
    this.res = res;
    console.log("this.res: "+ this.res); // this.res not undefined here
    Y();
});

function Y(){
    console.log("this.res: "+ this.res); // this.res here becomes undefined
});
user2498079
  • 2,324
  • 5
  • 26
  • 45

2 Answers2

0

This has to do with what we call scope. this inside a function is related to the specific scope of that function, thus, this.res in your case is always local to the functions where you are using it.

The correct way to access the global res would be to only use res, but you have another conflict that comes from the function argument with the same name.

I would suggest:

var res;

router.X('/yolo', jsonParser, function(req, _res, next) {
    res = _res;
    console.log("res: ", res);
    Y();
});

function Y(){
    console.log("res: ", res); // res will now have the correct value
});

P.S.: Also use , instead of + on console logs, so that the console outputs the full object tree.

Telmo Dias
  • 3,247
  • 2
  • 30
  • 41
0

The problem in Javascript is that global variables can not be set inside functions with this. In your case the variable returns undefined because res was not definded outside the functions. To solve this problem you can use

window.res

That means in your code:

var res;

/* GET home page. */
router.get('/', function(req, res, next) {
  window.res.render('index', { title: 'Express', shortenedUrl: ''});
});


router.X('/yolo', jsonParser, function(req, res, next) {
    window.res = res;
    console.log("this.res: "+ this.res);
    Y();
});

function Y(){
    console.log("this.res: "+ window.res); // it becomes no longer undefined
});

PS: It may be possible that I wrongly interpretet your code but I hope it will help you fixing your problem ;)

Talcore
  • 3
  • 2