JS,如何在调用 String.prototype.replace() 的替换函数中访问 "this"
JS, how to access to "this" in a replacer function in a call to String.prototype.replace()
我有这段代码:
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();
我看到错误:
Uncaught TypeError: Cannot read properties of undefined (reading '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());
我有这段代码:
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();
我看到错误:
Uncaught TypeError: Cannot read properties of undefined (reading '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());