javascript - 字符串无法读取未定义的属性 'replace'

标签 javascript string replace prototype undefined

我不知道我在这里缺少什么。

我在 utils.js 中将原型(prototype)设置为 String

String.prototype.toTitleCase = () => {
    return this.replace(/\w\S*/g, (txt) => {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

当我从 app.js 测试它时

import * as utils from 'utils'

"This is a test".toTitleCase();

我收到一个错误:TypeError: Cannot read property 'replace' of undefined

我认为原型(prototype)设计比创建一个函数更干净。这就是为什么我想了解。谢谢!

最佳答案

问题是您使用了 "Arrow function" .

An arrow function expression [...] lexically binds the this value

因此,当您创建函数时,this 的值被绑定(bind)到 undefined。它未绑定(bind)到您调用该函数的字符串对象。

要修复它,请使用常规函数:

String.prototype.toTitleCase = (function() {
    return this.replace(/\w\S*/g, (txt) => {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
});

关于javascript - 字符串无法读取未定义的属性 'replace',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39533352/

相关文章:

python - 用 X 相邻值的平均值替换 Numpy 数组中大于阈值的所有元素

javascript - 返回包含每个对象的命名属性的数组

javascript - WCF 服务在 GoDaddy 上无法运行,如何调试?

string - 显示Prec 和运算符优先级

用 "&"替换字符中的最后一个逗号

ruby - 用不同的字符串替换 Ruby 逗号

c# - 将 System.Drawing.Point 转换为 JSON。如何将 'X' 和 'Y' 转换为 'x' 和 'y'?

javascript - Vue 组件,切换数据

python - Perl 对应的 Python 前缀 r"text"的字符串文字?

ruby - ruby 字符串中的单个反斜杠