Similar Methods Across Objects in Javascript

How can you use methods of one object type against another object type? How can you use the feature to your advantage?

In another post, we had discussed how Javascript can use call to invoke methods of a function in a different context.

We can use this feature to our advantage.

Consider a string and array -

let alpha = ["a", "b", "c"];

const alphaCap = String.prototype.toUpperCase.call(alpha);
console.log("alphaCap: ", alphaCap.split(",")); // [ 'A', 'B', 'C' ]

Without explicitly converting alpha array, we can apply string manipulation methods directly on array. Did you note that the result was a string, and we had to convert back into an array. Yes, that happened.

The reverse is also possible.

let msg = "hello world";
Array.prototype.forEach.call(msg, val => console.log(val));
/* output
h
e
l
l
o

w
o
r
l
d
*/
comments powered by Disqus