0

As per Nested functions & the "this" keyword in JavaScript & https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

I understood that when a function is called directly(i.e.not with an object) , this should point to the global object.

In the below Node code , after the comment "//why is this null??" i thought "this" should be pointing to the global object. But it instead is "null"...why?

'use strict';

var fs = require('fs');

function FileThing() {
  this.name = '';

  this.exists = function exists(cb) {
    console.log('Opening: ' + this.name);
    fs.open(this.name, 'r', function onOpened(err, fd) {
      if (err) {
        if (err.code === 'ENOENT') { // then file didn't exist
          //why is this null??
          console.log(this);
          console.log('Failed opening file: ' + this.name);
          return cb(null, false);
        }
        // then there was some other error
        return cb(err);
      }
      fs.close(fd);
      return cb(null, true);
    });
  };
}

var f = new FileThing();
f.name = 'thisFileDoesNotExist';
f.exists(function onExists(err, exists) {
  if (err) {
    return console.log('ERROR! ' + err);
  }
  console.log('file ' + (exists ? 'DOES' : 'does NOT') + ' exist');
});
4
  • The Node code that invokes the callbacks can arrange for the value of this to be anything it wants. Commented Sep 27, 2015 at 12:20
  • so node explicitly sets this to null for some reason...so that we cant peek into the internals of global object? Commented Sep 27, 2015 at 12:36
  • 1
    I'm not sure - I can't find anything that documents that behavior. Note that in "strict" mode, lack of an explicit context for a function will result in this being undefined, not the global object. Commented Sep 27, 2015 at 12:37
  • Sorry, the answer you linked to was not entirely accurate, I did not differentiate between strict and sloppy mode there (fixed now). In your case I'd expect the this value to be undefined. Commented Sep 27, 2015 at 12:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.