Prototype basics with Dmitri

by Admiral Potato

HTML

<div id="output"></div>

CSS

.car{
    background-color: #eee;
    overflow: hidden;
    padding: 8px;
}

.car .name,
.car .color {
    display: block;
    margin: 2px;
    padding: 4px;
    background-color: #fff;
}
.car .name {
    background-color: #fde;
}

JavaScript

var output = document.getElementById('output');

var Car = function(name, color){
    this.name = name;
    this.color = color;
    this.buildElements();
};

Car.prototype = {
    buildElements: function(){
        this.holder = document.createElement('div');
        this.nameElement = document.createElement('span');
        this.colorElement = document.createElement('span');
        
        this.holder.className = 'car';
        this.nameElement.className = 'name';
        this.colorElement.className = 'color';
        
        this.nameElement.innerText = this.name;
        this.colorElement.innerText = this.color;
        
        this.holder.appendChild(this.nameElement);
        this.holder.appendChild(this.colorElement);
        
        output.appendChild(this.holder);
    }
};

var carList = [
    new Car('Ferarri', 'blue'),
    new Car('Lasagna', 'red'),
    new Car('Peperoni', 'green'),
    new Car('Canolli', 'purple')
];