【发布时间】:2017-07-19 11:13:42
【问题描述】:
我正在学习 Marc Wandscheider 的“Learning Node.JS”。我已经复制了这个代码用于一个类并调用;
let fs = require('fs');
function FileObject() {
this.filename = '';
this.file_exists = function(callback) {
console.log('About to open: ' + this.filename);
fs.open(this.filename, 'r', function(err, handle) {
if (err) {
console.log('Can\'t open: ' + this.filename);
callback(err);
return;
}
fs.close(handle, function() {});
callback(null, true);
});
};
}
let fo = new FileObject();
fo.filename = 'file_that_does_not_exist';
fo.file_exists((err, results) => {
if (err) {
console.log('\nError opening file: ' + JSON.stringify(err));
return;
}
console.log('file exists!!!');
});
运行时输出
About to open: file_that_does_not_exist
Can't open: undefined
未定义是因为fs.open() 方法的异步性质。作者通过添加一个变量将其存储在let self = this; 中来纠正这个问题
我想改用bind(this);,但不知道该怎么做!有没有使用self hack 的替代方法?
【问题讨论】:
标签: javascript node.js scope this