2016-09-16 24 views
1

我無法弄清楚我在這裏丟失了什麼。字符串無法讀取未定義的屬性'替換'

我設置了一個原型爲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

我想原型比創建一個功能更乾淨。這就是我想了解的原因。謝謝!

回答

2

的問題是,你使用的"Arrow function"

箭頭函數表達式[...]詞法結合此值

。因此this的值綁定到undefined在創建功能。它沒有綁定到你調用該函數的字符串對象。

要修復它,使用常規的功能:

String.prototype.toTitleCase = (function() { 
    return this.replace(/\w\S*/g, (txt) => { 
     return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); 
}); 
+0

謝謝!我正在發現es6,並且我認爲使用箭頭功能即可。 –

+0

當你想要詞法綁定時,箭頭功能非常棒。例如,通常會跳過諸如'var self = this;之類的箍環,以便在回調或承諾鏈中使用。箭頭功能非常棒。它們不太適合定義一個你想要傳統動態綁定'this'的原型。 – dsh

0

調試你的代碼,用你的返回行上的斷點檢查你的螢火蟲控制檯this的值,你會看到this不是一個字符串是代表你的String原型的對象。

1

this是Window對象,如果用箭頭功能,切換到正常的功能和它的作品

String.prototype.toTitleCase = function() { 
    return this.replace(/\w\S*/g, (txt) => { 
     return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); 
}; 
相關問題