TypeScript程序中出现意外的范围问题

时间:2015-06-26 21:02:24

标签: typescript this

下面的代码是我的第一个TypeScript程序。

在其中,我收到错误“无法调用未定义的方法推送”。我已经在下面的代码中添加了三个***标记的注释行,并且对这个编码的正确方法提出了疑问。

/// <reference path="typings/tsd.d.ts" />

import fs = require('fs');
import should = require('should');
var parse = require('csv-parse');

interface Question {
    number: number;
    text: string;
}

interface Answers {
    ordinal: number;
    text: string;
}

class CSVFile {
    fileName: string;
    rawRecords: string[];

    constructor() {
        this.rawRecords = [];
    }

    prepareFile(name: string) {
        this.fileName = name;
        var data = fs.readFileSync(name, "utf8");
        var parser = parse();
        var record;

        parser.on('readable', function() {
            while(record = parser.read()) {

// **** this.rawRecords is back to being undefined. I think it has to do
// **** with what this means in this spot. But how is the right way to
// *** do this? And why exactly is it failing?

                this.rawRecords.push(record);
            }
        });

        parser.on('error', function(err) {
            console.log("****: "+err.message);
        });

        parser.on('finish', function() {
            console.log("csv finished")
        });

        parser.write(data);
        parser.end();
    }

    recordCount(): number {
        return 0;
    }
}


var csv = new CSVFile();
csv.prepareFile("cs105spring2015.csv");

1 个答案:

答案 0 :(得分:3)

您已经失去了this。您可以在此处使用箭头功能来保留它:

    parser.on('readable', () => { // <-- replaced 'function'
        while(record = parser.read()) {
            this.rawRecords.push(record);
        }
    });