这在Javascript的回调中指向null

时间:2015-09-27 12:15:57

标签: javascript node.js callback this

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

我理解当直接调用函数时(即不使用对象),这应该指向全局对象。

在下面的节点代码中,在注释“//为什么是null?”之后我认为“这个”应该指向全球对象。但它反而是“空”......为什么?

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

0 个答案:

没有答案