Blog>
Snippets

'this' in Object Methods

Demonstrate 'this' usage within a method inside an object literal to refer to the object itself.
const person = {
  firstName: 'John',
  lastName: 'Doe',
  fullName: function() {
    // 'this' refers to the person object.
    // 'this.firstName' returns 'John'
    // 'this.lastName' returns 'Doe'
    return this.firstName + ' ' + this.lastName;
  }
};

console.log(person.fullName()); // Outputs: John Doe
Defines an object 'person' with properties 'firstName', 'lastName', and a method 'fullName'. The 'fullName' method uses 'this' to access the 'firstName' and 'lastName' properties of the 'person' object it belongs to.
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>'this' in Object Methods</title>
</head>
<body>
  <div id='output'></div>
  <script>
    // The JavaScript code
    const person = {
      firstName: 'John',
      lastName: 'Doe',
      fullName: function() {
        return this.firstName + ' ' + this.lastName;
      }
    };

    document.getElementById('output').textContent = person.fullName();
  </script>
</body>
</html>
HTML code with embedded JavaScript. JavaScript defines an object 'person' with a method 'fullName' that uses 'this'. The result is displayed in the 'output' <div> element.
body {
  font-family: 'Arial', sans-serif;
}
CSS code that styles the <body> text with the Arial font. This CSS can be included in the <head> section of the HTML document within a <style> tag.