这是类(忽略我尝试调试时遗留的console.logs)
import fs = require('fs');
export interface Answer {
order: number,
text: string
}
export class Config {
answers:Answer[];
timestamp_column: string;
name_column: string
fromJSONFile(fileName: string) {
var fileString = fs.readFileSync(fileName);
this.answers = JSON.parse(fileString.toString());
console.log(this.answers);
}
mapAnswerToNum(answer:string):number {
console.log(typeof this.answers);
for (var a in this.answers) {
if (a.text == answer) { return a.order;}
}
for (var a in this.answers) {
console.log(a.text);
}
console.log(typeof this.answers);
throw new Error(`Invalid response string ${answer}`);
}
}
这是调用:
import { Config } from './config';
var config = new Config();
config.fromJSONFile("./csvconfig.json");
...
var respInts:number[] = respStrings.map(this.config.mapAnswerToNum);
...
问题:在mapAnswerToNum的正文中,似乎this.answers
未定义,即使在fromJSONFile
的正文中 。
我被this
冲洗了吗?编码我的意图的正确方法是什么?
答案 0 :(得分:1)
由于在mapAnswerToNum
的原型上定义了Config
,因此传递给map
的函数是在Config
的所有实例之间共享的函数。所以在这种情况下,上下文正在丢失。
您可以通过将代码更改为以下内容来解决此问题:
var respInts:number[] = respStrings.map((respString) => this.config.mapAnswerToNum(respString));
这会在mapAnswerToNum
的实例上调用this.config
。
以下是一个例子:
class Config {
mapAnswerToNum() {
console.log(this);
}
}
输出:
var Config = (function () {
function Config() {
}
Config.prototype.mapAnswerToNum = function () {
console.log(this);
};
return Config;
})();
因此在使用时:
function dummyArrayMap(func) {
func();
}
var config = new Config();
// logs window since this function is shared across all instances of `Config`.
dummyArrayMap(config.mapAnswerToNum); // the context is lost.
// logs the instance of config since we called the function on the instance
dummyArrayMap(() => config.mapAnswerToNum());
替代所有这些,您可以在mapAnswerToNum
上使用箭头功能。这不是我喜欢的解决方案,因为那时函数不再是原型。我将通过上面的例子演示它:
class Config {
mapAnswerToNum = () => {
console.log(this);
}
}
输出:
var Config = (function () {
function Config() {
var _this = this; // notice this is saved here
this.mapAnswerToNum = function () {
console.log(_this); // then used here
};
}
return Config;
})();
因此在使用时:
var config = new Config();
dummyArrayMap(config.mapAnswerToNum); // logs config
dummyArrayMap(() => config.mapAnswerToNum()); // logs config