What are objects, how are they are created and what we can do with them? In this lesson we learn how to create our own
Object instances and assign property values
to them. We also look at the
delete special operator which allows us to delete object properties.
String and the subject of our first lesson on objects,
var objectName = new Object;
We can then add new properties to our created object in the form of name/value pairs with the syntax:
objectName.someProperty = someValue;
Object properties are created through assignment without any need to declare the property in advance.
The following code creates a homeOwner object.
/* Create an object that holds first and last name properties */ var homeOwner = new Object(); homeOwner.firstName = 'Teddy'; homeOwner.surname = 'Bear'; alert('Homeowner name is: ' + homeOwner.firstName + ' ' homeOwner.surname);
Deleting Object Properties
The following code creates a homeOwner object with a typo for the surname property. When we try to display that property it is
undefined as it doesn't exist. We then
delete the misspelt operator using the
delete special operator and define the property correctly. The property now displays properly and the typo is now deleted
undefined. We can also use the
set special operators to get and set object properties. These special operators are covered in the reference section if you want to see them coded.
*/ / Create an object that holds first and last name properties with a typo / for surname (surnaem). Be careful when assigning object properties. /* var homeOwner = new Object(); homeOwner.firstName = 'Teddy'; homeOwner.surnaem = 'Bear'; alert('Homeowner is: ' + homeOwner.firstName + ' ' + homeOwner.surname); alert('Misspelt property value: ' + homeOwner.surnaem); // typo // Delete typo using delete operator and create the correct property delete homeOwner.surnaem; homeOwner.surname = 'Bear'; alert('Homeowner is: ' + homeOwner.firstName + ' ' + homeOwner.surname); alert('Misspelt property value: ' + homeOwner.surnaem);
You can also nest objects, to any level, within other objects.
// Create a name object that holds first and last name properties var homeOwner = new Object(); homeOwner.firstName = 'Teddy'; homeOwner.surname = 'Bear'; // Create an address object. var anAddress = new Object(); anAddress.number = 12; anAddress.street = 'Picnic Street'; anAddress.town = 'Toytown'; /* We are nesting the homeOwner object we created above in our address object. */ anAddress.owner = homeOwner; /* We could access nested values as follows: */ alert(anAddress.street); alert(anAddress.owner.surname);
Lesson 7 Complete
There are more elegant ways to create objects which we will cover later, in the Intermediate section of the course.
get special operator
delete special operator
new special operator
set special operator