Social Icons

Pages

Thursday, December 1, 2016

Introduction to Objects I 25/33

Constructors in Review
Constructors are a way to make objects with the keyword new. The most basic constructor is the Object constructor, which will make an object with no methods or properties.
For more complicated objects we can make our own constructors and put in whatever properties and methods we want.
Check out our example to the right to see objects in action. Our Rabbit constructor defines an adjective property and adescribeMyself method.
Recall how these kind of custom constructors are important because they allow us to easily make many similar objects.

Instructions
Create a new object rabbit1 with the adjective "fluffy", a new object rabbit2 with the adjective "happy", and a new objectrabbit3 with the adjective "sleepy".
Use the method describeMyself to print out in the console a sentence about each object you just created!
function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
    };
}
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

No comments:

Post a Comment