Reading MDN docs and have found this code:
const a = String.prototype.toUpperCase.call({
toString: function toString() {
return 'abcdef';
}
});
// prints out 'ABCDEF'
Function call takes as first argument object with method toString, which means calling a function toUpperCase() on object or (correct me please if I’m wrong):
({ toString: function toString() { return 'abcdef'; }}).toUpperCase()
This code prints out ‘ABCDEF’, so how could toUpperCase() method invoke function toString() inside object that’s what I don’t understand.
>Solution :
You’re calling toUpperCase passing it an object that isn’t a string but which has a toString method. Contrary to popular belief, toUpperCase doesn’t assume this will be a string. Instead, it converts whatever this is (in your case, the object with a toString method) to a string as one of its first steps (see the spec here¹). Doing that calls the toString method of your object (details here and here). At that point, toUpperCase has "abcdef" to work with, converts it to upper case, and returns it.
Conceptually (not exactly), toUpperCase does this:
function toUpperCase() {
const S = String(this); // This is what triggers the call to `toString`
// on your object
const L = /*...convert the characters in S to to upper case*/;
return L;
}
¹ That’s for toLowerCase, but toUpperCase is defined by saying "This function behaves in exactly the same way as String.prototype.toLowerCase, except that the String is mapped using the toUppercase algorithm of the Unicode Default Case Conversion."