javascript - 如何将此原型函数转换为 es6?
问题描述
// Converts snake-case to camelCase
String.prototype.toCamel = function () {
return this.replace(/(\-[a-z])/g, $1 => $1.toUpperCase().replace('-', ''));
};
当我执行以下操作时:
// Converts snake-case to camelCase
String.prototype.toCamel = () => this.replace(/(\-[a-z])/g, $1 => $1.toUpperCase().replace('-', ''));
我收到此错误:
modifiers.js:9 未捕获类型错误:无法读取未定义的属性“替换”
我如何使用该toCamel
功能:
// Add style to coin
export const setStyle = (id) => {
switch (id) {
case 'basic-attention-token': return style.basicattentiontoken;
case 'bitcoin-cash': return style[id.toCamel()];
case 'deepbrain-chain': return style[id.toCamel()];
case '0x': return style.zrx;
default: return style[id];
}
};
解决方案
箭头函数具有词法绑定,因此您不能this
以您想要的方式使用。如果您拥有this
的是未定义的并且您无法读取它的“替换”属性。
推荐阅读
- javascript - 在滚动 laravel ajax 上加载更多数据
- node.js - 如何附加到 Node.js 中的文件但将文件限制为特定大小
- node.js - 我们可以在 mongo 中使用什么字段类型来存储对象数组?
- powershell - 如何通过 PowerShell 使用 Azure DevOps 的内部版本号更新 AssemblyInfo.cs 中的 AssemblyVersion 号?
- r - R如何使用stackApply计算每年的季节性平均值?
- php - Mootools JSON 请求返回未找到错误
- java - 没有为 TestNG 执行测试
- c# - 在新的非空测试中使用 ref 原则
- tailwind-css - TailwindCSS 焦点 + CSS 文件中的占位符
- c++ - 从对象数组中删除元素