首页 > 解决方案 > 如何将此原型函数转换为 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];
  }
};

标签: javascriptecmascript-6prototype

解决方案


箭头函数具有词法绑定,因此您不能this以您想要的方式使用。如果您拥有this的是未定义的并且您无法读取它的“替换”属性。


推荐阅读