This page looks best with JavaScript enabled

Method of a Function in Javascript

 ·   ·  ☕ 2 min read

A function can have its own methods - strange but true. Why? Because everything in Javascript is an object and object can have methods.

Consider -

1
2
3
4
5
6
function getSum(x, y) {
  return x + y;
}

console.log(getSum(1, 2)); //3
console.log(getSum.call(this, 1, 2)); //3

The first call to getSum is as expected. The second call uses a method called call and passes this as the argument along with the two numbers. This is equivalent to the first call.

Or, use call's friend apply -

1
console.log(getSum.apply(this, [1, 2])); //3

Everything stays the same except that the params are sent in an array.

The above example may not seem that useful. Let’s see a marginally better example.

1
2
3
4
5
6
7
8
const fruit = {
  color: "green",
  getColor: function() {
    return this.color;
  }
};

console.log(fruit.getColor()); // green

We are calling a function of an object to get and print color - nothing amazing.

We will create another object but leave out the function-

1
2
3
const apple = {
  color: "red"
};

We cannot obviously call getColor from apple.

1
2
console.log(apple.getColor());
// TypeError: apple.getColor is not a function

But, an amazing thing happens when we do this -

1
console.log(fruit.getColor.call(apple)); //red

This call invokes fruit's function in apple context. So, just like that we are reusing functions across objects that are not related, but just had common props.

The use of such methods may seem bewildering at first - but you had been doing it all along. How do you think methods work as expected across objects & arrays, arrays & strings, and so on?

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things