JavaScript Function call()


Method Reuse

You can create a method that works on various objects using the call() method.


All Functions are Methods

In JavaScript, every function is a method of an object.

If a function is not part of a JavaScript object, it's a function of the overall/global object (refer to the previous chapter).

The following example generates an object with three characteristics: firstName, lastName, and fullName.

In the sample provided, this points to the person object.

this.firstName refers to the firstName attribute of the current object (this).

Same as:

this.firstName refers to the firstName attribute of a person.


What is this?

In JavaScript, when we use the this keyword, it points to an object.

Which object that relies on how this is invoked (used or called).

The word "this" means different things based on how it's used:

In a method related to an object, the keyword this points to the specific object.
By itself, the term this points to the overall object known as the global object.
In a function, the term this points to the overall object known as the global object.
In a function, when in strict mode, the value of this is undefined.
At an event, this means the element that got the event.
HTML methods such as call(), apply(), and bind() can make the reference of this point to any object.

Note

this is not like a variable; it's a keyword. You can't alter the value of this.

See Also:

The JavaScript this Tutorial


The JavaScript call() Method

The call() method in JavaScript is already set up and ready to use.

You can use it to call a method, providing an owner object as an argument.

Using call(), an object can utilize a method that belongs to a different object.

This example uses the fullName method of a person and applies it to person1.

This instance invokes the fullName function of a person, applying it to person2:

The call() Method with Arguments

The call() method can take in information or values known as arguments: