I was following an online lesson for beginners, which used the apply/bind methods to set the 'this' context for a function.
I saw that you can chain the bind method directly to the function block, which was new to me. So it got me thinking why cant I chain other methods, other than bind/call/apply, to affect the returned value.
let obj = {
name: 'john',
};
let sayHello = function() {
return 'hello there ' + this.name;
}.apply(obj).toUpperCase();
let sayBonjour = function() {
return 'Bonjour!';
}.toUpperCase();
console.log(sayHello);
console.log(sayBonjour());
In the example above why can I use the .toUpperCase() method on the sayHello function which uses the apply method, and not on the sayBonjour function which does not. In trying to do so I get the error:
'Uncaught TypeError: (intermediate value).toUpperCase is not a function'.
I realize this is not the way string method (or other methods) is/are intended to be used, for learning purposes, I was hoping someone could explain whats preventing me from using the method in such a way.
Many thanks for your time and help
bind,callandapplybut nottoUpperCaseis that there is no such method inFunction.prototype(that is, there is noFunction.prototype.toUpperCase()). Have a look at the list here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. AstoUpperCase()is a method present inString.prototypethe IIFE in the answer below will work, since the function itself returns a string.