Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Invoking a Function as a Method

In JavaScript, you can define functions as methods of an object.

The following example creates an object (myObject) with two properties (firstName and lastName), and a method (fullName):

Example

const myObject = {
  firstName:“John”,
  lastName: “Doe”,
  fullName: function () {
    return this.firstName + ” “ + this.lastName;
  }
}
myObject.fullName();         // Will return “John Doe”

The fullName method belongs to myObject, making it the owner. The this keyword refers to the object that owns the method. Try modifying fullName to return this.

Example

const myObject = {
  firstName:“John”,
  lastName: “Doe”,
  fullName: function () {
    return this;
  }
}

// This will return [object Object] (the owner object)
myObject.fullName();
When a function is invoked as a method of an object, the value of this refers to the object itself.