TypeScript 程序中的意外范围问题
Unexpected scoping issue in a TypeScript program
下面的代码是我的第一个 TypeScript 程序。
其中,我收到一个错误 "cannot call method push of undefined"。我包含了三个 ***
标记的注释行,与下面的代码一致,并提出了有关正确编码方式的问题。
/// <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");
您丢失了 this
。您可以在此处使用箭头函数来保留它:
parser.on('readable', () => { // <-- replaced 'function'
while(record = parser.read()) {
this.rawRecords.push(record);
}
});
下面的代码是我的第一个 TypeScript 程序。
其中,我收到一个错误 "cannot call method push of undefined"。我包含了三个 ***
标记的注释行,与下面的代码一致,并提出了有关正确编码方式的问题。
/// <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");
您丢失了 this
。您可以在此处使用箭头函数来保留它:
parser.on('readable', () => { // <-- replaced 'function'
while(record = parser.read()) {
this.rawRecords.push(record);
}
});