This page looks best with JavaScript enabled

Similar Methods Across Objects in Javascript

 ·   ·  ☕ 1 min read

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 -

1
2
3
4
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
let msg = "hello world";
Array.prototype.forEach.call(msg, val => console.log(val));
/* output
h
e
l
l
o

w
o
r
l
d
*/
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things