-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16_Override_toString.js
More file actions
27 lines (23 loc) · 865 Bytes
/
16_Override_toString.js
File metadata and controls
27 lines (23 loc) · 865 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 16. How to override toString on String.prototype?
*
* You can override methods on built-in prototypes, though it's generally discouraged ("Monkey Patching") as it affects all instances globally and can break libraries.
*/
/*
// WARNING: This affects ALL strings in the application
const originalToString = String.prototype.toString;
String.prototype.toString = function() {
return 'Overridden: ' + originalToString.call(this);
};
const str = "Hello";
console.log(str.toString()); // "Overridden: Hello"
console.log(`${str}`); // "Overridden: Hello" (template literals use toString)
*/
// A safer approach is to override it on a specific object/class instance
class MyString extends String {
toString() {
return `Custom: ${super.toString()}`;
}
}
const myStr = new MyString("World");
console.log(myStr.toString()); // "Custom: World"