JS,如何在调用 String.prototype.replace() 时访问替换器函数中的"this"



我有一段代码:

class MyClass {
constructor(text, pattern) {
this.text = text;
this.pattern = pattern;
}
run() {
return this.text.replace(/(d)/, this.replacer)
}
replacer(match, timeString, offset, string) {
return this.pattern;
}
}

这是我实际代码的一个简化示例。

当我运行时:

var v = new MyClass("text 1 2", "X");
v.run();

我看到错误:

未捕获类型错误:无法读取未定义(读取"pattern"(的属性

如何访问此替换函数中的this

使用Function#bind来设置this值,或者使用调用this.replacer的箭头函数作为回调。

class MyClass {
constructor(text, pattern) {
this.text = text;
this.pattern = pattern;
}
run() {
return this.text.replace(/(d)/, this.replacer.bind(this));
// or return this.text.replace(/(d)/, (...args) => this.replacer(...args));
}
replacer(match, timeString, offset, string) {
return this.pattern;
}
}
var v = new MyClass("text 1 2", "X")
console.log(v.run());

最新更新