这在Javascript中的回调中指向null
根据, 我知道,当直接调用函数时,即不使用对象调用函数时,应该指向全局对象 在下面的节点代码中,注释//why is null??我认为这应该指向全局对象。但是它是空的…为什么这在Javascript中的回调中指向null,javascript,node.js,callback,this,Javascript,Node.js,Callback,This,根据, 我知道,当直接调用函数时,即不使用对象调用函数时,应该指向全局对象 在下面的节点代码中,注释//why is null??我认为这应该指向全局对象。但是它是空的…为什么 'use strict'; var fs = require('fs'); function FileThing() { this.name = ''; this.exists = function exists(cb) { console.log('Opening: ' + this.name);
'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');
});
调用回调的节点代码可以将其值设置为它想要的任何值。因此,由于某种原因,节点显式将其设置为null…这样我们就无法窥视全局对象的内部了?我不确定-我找不到任何记录该行为的内容。请注意,在严格模式下,缺少函数的显式上下文将导致该函数未定义,而不是全局对象。抱歉,您链接到的答案不完全准确,我没有区分严格模式和草率模式。在你的情况下,我希望这个值是未定义的。