Social Icons

Pages

Wednesday, November 30, 2016

Introduction to Objects I 10/33

Another Way to Create
The method we've used to create objects usesobject literal notation—that is, creating a new object with { } and defining properties within the brackets.
Another way of creating objects without using the curly brackets { } is to use the keywordnew. This is known as creating an object using a constructor.
The new keyword creates an empty object when followed by Object(). The general syntax is:
var objectName = new Object();
We then have to fill this object with properties and labels. How do we do that? Check out the creation of the object bob to see what we do. We create the name property for the objectbob by using bob.name and assigning that to a value. Contrast this to how we define properties in lines 6-7 for the susan1 object.

Instructions
Inspect the susan1 object carefully and note the use of object literal notation.
Use constructor notation to create susan2, which should have the same properties and values as susan1.

// Our bob object again, but made using a constructor this time
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
// Here is susan1, in literal notation
var susan1 = {
  name: "Susan Jordan",
  age: 24
};
// Make a new susan2 object, using a constructor instead
var susan2 = new Object();
susan2.name = "Susan Jordan";
susan2.age = 24;

No comments:

Post a Comment