viernes, 6 de abril de 2012

Javascript Patterns 1 (Constructors)

One of the first design pattern you must know is the "Constructor pattern", which lets you create objects/classes in Javascript. Classes dont exist in JavaScript, but we can "simulate" them with functions.


Basic Constructor

function Car(model, color) {
    this.Model = model;
    this.Color = color;

    this.ToString = function() {
        return "Model: " + this.Model + ", Color: " + this.Color;
    }
}

Constructor using Prototypes

function Car(model, color) {
    this.Model = model;
    this.Color = color;
}

Car.prototype.ToString = function() {
    return "Model: " + this.Model + ", Color: " + this.Color;
}

No hay comentarios:

Publicar un comentario