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');
});