Thursday, April 18, 2013

Javascript: Construction Junctions

chocolate green tea lava cake @ spot dessert bar 


constructor is a way to create an object. So far, we've been using a built-in constructor called Object. Already defined by the JS language, it creates an object with no properties/methods.
var thecutedork = new Object();
thecutedork.url = "http://hellocutedork.blogspot.com";
thecutedork.platform = "blogger"

However, don't you agree that this makes adding properties one at a time for every single object kind of tedious? Well, we can create our own constructions. This way, we can actually set the properties for an object right when it is created!

function Blog(url, platform) {
  this.url = url;
  this.platform = platform;



// let's make goodwillgrrl and mdfrmscrtch, using our constructor:
var goodwillgrrl = new Blog("http://goodwillgrrl.blogspot.com ", "blogger")
var mdfrmscrtch = new Blog("http://mdfrmscrtch.blogspot.com", "blogger")

In addition to setting properties, constructors can also define methods.

/* here is a Rectangle constructor, which sets the length and width properties equal to the arguments, just like our Blog constructor did with url and platform.

Notice the calcArea method. This calculates the area of the rectangle in terms of its length and width. */

function Rectangle(length, width) {
  this.length = length;
  this.width = width;
  this.calcArea = function() {
    return this.length * this.width;
}; 
}

var rex = new Rectangle(7,3);
var area = rex.calcArea();

/* Constructors are a way to make objects with the keyword new. We have one final example of a constructor which defines an adjective property and adescribeMyself method: /*

function Rabbit(adjective) {
  this.adjective = adjective;
  this.describeMyself = function(){
    console.log("I am a " + this.adjective + " rabbit");
  };
}

// now we can easily make all of our rabbits:
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

rabbit1.describeMyself();

rabbit2.describeMyself();
rabbit3.describeMyself();

No comments:

Post a Comment