Search code examples
javascriptecmascript-6prototype

How to convert this prototype function into es6?


// 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];
  }
};

Solution

  • 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.