我不知道我在这里缺少什么。
我在 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/