如何在Node.js中的fs.readFile中使用'this'引用

时间:2014-02-04 16:13:38

标签: javascript node.js this readfile

我想使用fs.readFile方法使用我的JavaScript类的this关键字从文件填充对象列表

var MyReaderClass = (function() {
    //Const    

    function MyReaderClass() {
        this.readObjects = [];

        /**    
         * Default constructor for the MyReaderClass class
         */
        var _constructor = function() {

        }

        _constructor.call(this);
    }

    //Public    
    MyReaderClass.prototype.ReadFiles = function(p_path) {
        var files = fs.readdirSync(p_path);

        for (var i in files) {
            var fileName = files[i];
            fs.readFile(path.join(p_path, fileName), 'utf8', function(err, data) {
                if (err) {
                    return console.log(err);
                } 
                else {
                    var formattedData = /*... Logic to format my data into an object*/;
                    this.readObject.push(formattedData); //The "this" is not the reference to my class.
                }
            });
        }
    }
    return MyReaderClass;
})();

即使我在_self, that, instance, etc.方法之外创建我的此变量的本地实例(readFile),我的本地实例也不会被填满。

知道我怎么能做到这一点吗?

1 个答案:

答案 0 :(得分:3)

readFile是异步方法,您丢失了execute context。您需要将您的类绑定到readFile回调作为上下文。使用Function.prototype.bind

MyReaderClass.prototype.ReadFiles = function(p_path) {
    var files = fs.readdirSync(p_path);
    for (var i in files) {
        var fileName = files[i];
        fs.readFile(path.join(p_path, fileName), 'utf8', function(err, data) {
            /*readFile callback*/
        }.bind(this));//also here was a syntax error
    }
}