我無法弄清楚我在這裏丟失了什麼。字符串無法讀取未定義的屬性'替換'
我設置了一個原型爲String我utils.js
String.prototype.toTitleCase =() => {
return this.replace(/\w\S*/g, (txt) => {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
;當我從app.js測試
import * as utils from 'utils'
"This is a test".toTitleCase();
我得到一個錯誤:TypeError: Cannot read property 'replace' of undefined
我想原型比創建一個功能更乾淨。這就是我想了解的原因。謝謝!
謝謝!我正在發現es6,並且我認爲使用箭頭功能即可。 –
當你想要詞法綁定時,箭頭功能非常棒。例如,通常會跳過諸如'var self = this;之類的箍環,以便在回調或承諾鏈中使用。箭頭功能非常棒。它們不太適合定義一個你想要傳統動態綁定'this'的原型。 – dsh