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>
So far we've only looked at retrieving (or getting) object members – you can also set (update) the value of object members by declaring the member you want to set (using dot or bracket notation), like this:
person.age = 45; person['name']['last'] = 'Cratchit';
Try entering the above lines, and then getting the members again to see how they've changed, like so:
person.age person['name']['last']
Setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members. Try these in the JS console:
person['eyes'] = 'hazel'; person.farewell = function() { alert("Bye everybody!"); }
You can now test out your new members:
person['eyes'] person.farewell()
One useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. Let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. We could get those values like this:
let myDataName = nameInput.value; let myDataValue = nameValue.value;
We could then add this new member name and value to the person object like this:
person[myDataName] = myDataValue;
To test this, try adding the following lines into your code, just below the closing curly brace of the person object:
let myDataName = 'height'; let myDataValue = '1.75m'; person[myDataName] = myDataValue;
Now try saving and refreshing, and entering the following into your text input:
person.height
Adding a property to an object using the method above isn't possible with dot notation, which can only accept a literal member name, not a variable value pointing to a name.