1
// Converts snake-case to camelCase
String.prototype.toCamel = function () {
  return this.replace(/(\-[a-z])/g, $1 => $1.toUpperCase().replace('-', ''));
};

When I do the following:

// Converts snake-case to camelCase
String.prototype.toCamel = () => this.replace(/(\-[a-z])/g, $1 => $1.toUpperCase().replace('-', ''));

I get this error:

modifiers.js:9 Uncaught TypeError: Cannot read property 'replace' of undefined

How I'm using that toCamel function:

// 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];
  }
};
Leon Gaban
  • 36,509
  • 115
  • 332
  • 529
  • Possible duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – Scott May 23 '18 at 01:06
  • The question's title is misleading. In your example you don't convert anything to ES6. You replace a regular function with an arrow function, which doesn't make any sense in this case. – a better oliver May 23 '18 at 10:14
  • An arrow function is es6 – Leon Gaban May 24 '18 at 18:49

2 Answers2

4

Arrow functions have lexical binding, so you can't use this in the way that you want to. In the case you have this is undefined and you can't read property 'replace' of it.

Brett East
  • 4,022
  • 2
  • 20
  • 31
0

The issue is that you are using an Arrow function.

An arrow function expression is lexically binding the this value. So, the value is bound to undefined. You have to use the normal function.

user3619911
  • 107
  • 1
  • 9