覆蓋 String.replace() 對物件的行為
前言
在研究 Symbol 時發現可以覆蓋 String.replace() 對物件的行為,在此把學習的過程做紀錄。
內容
String.replace() 對物件的行為預設是會回傳原本的字串,透過覆蓋可以改變該行為,範例如下
class Replace1 {
constructor(value) {
this.value = value;
}
[Symbol.replace](string) {
return `${string} replace ${this.value}`;
}
}
let obj ={};
obj[Symbol.replace] = function(string){
return "I am cusutom replace.";
}
console.log('foo'.replace(new Replace1('bar')));//"foo replace bar"
console.log('foo'.replace(obj) );//"I am cusutom replace."
覆蓋的做法是在要被覆蓋的物件裡定義覆蓋 function ,透過 Symbol.replace 來指名覆蓋,範例示範在 class 與 object 的覆蓋,覆蓋 function 的參數是來源的 String ,也就是喚起 replace() 的 String。
沒有留言:
張貼留言