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

String Cannot read property 'replace' of undefined

我不知道我在这里遗漏了什么。

我在 utils.js

中将原型设置为字符串
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

我认为制作原型比创建一个函数更干净。这就是为什么我想了解。谢谢!

调试您的代码,检查您的 firebug 控制台,在 return 行上设置一个断点 this 的值,您将看到 this 是不是字符串是表示您的字符串原型的对象。

this 是 Window 对象 如果使用箭头函数,切换到普通函数就可以了

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

问题是您使用了 "Arrow function"

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

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

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

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