Practice: Exploring Objects Using JavaScript

In this section, you'll use JavaScript to create a "person" object. The code can be run in any browser and uses the Developer Console. This practice exercise does not count towards your grade. It is just for practice!

Here are the contents of the file:

<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<title>Object-oriented JavaScript example</title>
</head>
<body>

<p>This example requires you to enter commands in your browser's JavaScript console
(see What are browser developer tools for more information).</p>

</body>

<script>

</script>
</html>

You may have noticed something slightly strange in our methods. Look at this one for example:

greeting: function() {
  alert('Hi! I\'m ' + this.name.first + '.');
}

You are probably wondering what "this" is. The this keyword refers to the current object the code is being written inside – so in this case this is equivalent to person. So why not just write person instead? As you'll see in the Object-oriented JavaScript for beginners article, when we start creating constructors and so on, this is very useful – it always ensures that the correct values are used when a member's context changes (for example, two different person object instances may have different names, but we want to use their own name when saying their greeting).

Let's illustrate what we mean with a simplified pair of person objects:

const person1 = {
  name: 'Chris',
  greeting: function() {
    alert('Hi! I\'m ' + this.name + '.');
  }
}

const person2 = {
  name: 'Deepti',
  greeting: function() {
    alert('Hi! I\'m ' + this.name + '.');
  }
}

In this case, person1.greeting() outputs "Hi! I'm Chris."; person2.greeting() on the other hand outputs "Hi! I'm Deepti.", even though the method's code is exactly the same in each case. As we said earlier, this is equal to the object the code is inside – this isn't hugely useful when you are writing out object literals by hand, but it really comes into its own when you are dynamically generating objects (for example using constructors). It will all become clearer later on.