簡體   English   中英

如何將此原型函數轉換為es6?

[英]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('-', ''));
};

當我執行以下操作時:

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

我收到此錯誤:

Modifiers.js:9未捕獲的TypeError:無法讀取未定義的屬性“替換”

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

箭頭函數具有詞法綁定,因此您無法以所需的方式使用this 在這種情況下, this是未定義的,您將無法讀取其“替換”屬性。

問題是您正在使用箭頭功能。

箭頭函數表達式用詞法綁定了this值。 因此,該值綁定到undefined 您必須使用正常功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM