Trung Tran
Trung Tran

Reputation: 229

What is 'this' refering to?

I know that 'this' refers to object of the function using 'this'. So in this case, which object 'this' in the function(req, res) is referring to?

router.post('/upload', function(req, res, next) {
  console.log(this);
  console.log(dir);
  ...
}

Upvotes: 1

Views: 109

Answers (2)

slebetman
slebetman

Reputation: 113866

It depends on how router.post() calls the callback. The first place to look is the documentation. If it's not documented then look at the code. In general, one may assume that if there is no special handling of this then it points to the global object (or undefined if in strict mode).

If router.post() is implemented like this:

router.post = function (route, callback) {
    // ..
    callback(a,b,c);
}

then this will point to the global object or undefined depending on weather or not you "use strict".

But router.post() can also be implemented like this:

router.post = function (route, callback) {
    // ..
    callback.call(something,a,b,c);
}

in which case this will point to whatever that something is.

Or it could also be implemented like this:

router.post = function (route, callback) {
    // ..
    var foo = {
       a : callback
    }
    a(a,b,c);
}

in which case this will point to the foo object.

As you can see, in javascript the caller determines the value of this.

See my answer to this related question to understand how this behaves in javascript: How does the "this" keyword in Javascript act within an object literal?


Additional answer:

If you've read the link above then you'd also realize that you can force this to be whatever you want it to be using bind or a closure:

router.post('/upload', (function(req, res, next){
    console.log(this); // prints whatever myThis below points to
    console.log(dir);
}).bind(myThis));

Upvotes: 3

Smallcampus Tin
Smallcampus Tin

Reputation: 1

According to doc, this refer to the owner of the object. In your case, the owner of the function should be defined in the router.post (if any)

//Definition of router.post
router.post = function(string, block) {    
    block(x,y,z);
}

and in this case, this should have no owner? Usually when I use "this", I need to use the keyword "new"

function Foo()
{
    this.a = 1;
}

var foo = new Foo();
console.log(foo.a);  // 1

Upvotes: 0

Related Questions