【问题标题】:How to convert this prototype function into es6?如何将此原型函数转换为 es6?
【发布时间】:2018-05-22 21:23:19
【问题描述】:
// 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 Uncaught TypeError: Cannot read property 'replace' of undefined

我如何使用 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];
  }
};

【问题讨论】:

标签: javascript ecmascript-6 prototype


【解决方案1】:

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

【讨论】:

  • 那么有没有办法做到这一点呢?它必须留在function
  • @LeonGaban 没错,目前你必须继续使用function
【解决方案2】:

问题在于您使用的是箭头函数。

箭头函数表达式在词法上绑定this 值。因此,该值绑定到undefined。您必须使用普通功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2015-08-23
    • 1970-01-01
    • 2023-01-29
    • 2020-03-07
    • 2018-12-04
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多