javascript - 如何将这个原型(prototype)函数转换成es6?

标签 javascript ecmascript-6 prototype

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

最佳答案

箭头函数有词法绑定(bind),所以你不能按你想要的方式使用this。如果您有 this 是未定义的,您无法读取它的“替换”属性。

关于javascript - 如何将这个原型(prototype)函数转换成es6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50476640/

相关文章:

javascript - 使用 JSX 在 <code> 标签内渲染 JavaScript

reactjs - 将状态从子组件传递到父组件

jquery - Firefox + firebug,原型(prototype) + jquery.noconflict : Firefox crashes on page load

Javascript初学者if.else切换转换

javascript - super 方法为 Es6 中定义的变量返回未定义

Javascript 原型(prototype)作用域和递归问题

javascript - 使用原型(prototype)扩展 Javascript Form 对象

javascript - Odoo 10 添加按钮到 POS

javascript - 元素为数组时两个数组之间的区别

javascript - $(this) 不同于 $.each 循环上下文中的 'element' 参数