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 accessed the object's properties and methods using dot notation. The object name (person) acts as the namespace – it must be entered first to access anything encapsulated inside the object. Next you write a dot, then the item you want to access – this can be the name of a simple property, an item of an array property, or a call to one of the object's methods, for example:
person.age person.interests[1] person.bio()
Sub-namespaces
It is even possible to make the value of an object member another object. For example, try changing the name member from
name: ['Bob', 'Smith'],
to
name : { first: 'Bob', last: 'Smith' },
Here we are effectively creating a sub-namespace. This sounds complex, but really it's not – to access these items you just need to chain the extra step onto the end with another dot. Try these in the JS console:
person.name.first person.name.last
Important: At this point you'll also need to go through your method code and change any instances of
name[0] name[1]
to
name.first name.last
Otherwise your methods will no longer work.