Object creating sample

by qfox

HTML

<pre>

JavaScript

// generator Box
var Box = function(tag, cls) {
    this.tag = tag || 'div';
    this.cls = cls || '';
    return this;
};
Box.prototype.toString = function() {
    return '<'+this.tag+' class="'+this.cls+'"></'+this.tag+'>';
};

// create new generator Boxie and extend it
var Boxie = function Boxie(tag, cls, content, width, height) {
    Box.apply(this, arguments); // some magic. parent call
    this.width = width || 300;
    this.height = height || 300;
    this.content = content || 'usual boxie block';
    this.cls = cls || 'usual-boxie'; // overwrite
    return this;
};
Boxie.prototype = new Box();
Boxie.prototype.toString = function() {
    return '<'+this.tag+' class="'+this.cls+'" ' +
        'style="width:'+this.width+'px; height:'+this.height+'px;">' +
        this.content +
        '</'+this.tag+'>';
};

function htmlentities(text){
    var r = document.createElement('div');
    r.appendChild(document.createTextNode(''+text));
    return r.innerHTML;
}

var testBox = new Box();
document.writeln( 'box: ' + htmlentities(testBox) );

var testBoxie = new Boxie();
document.writeln( 'boxie: ' + htmlentities(testBoxie) ); // toString hidden call
// out: boxie: <div class="usual-boxie" style="width:300px; height:300px;">usual boxie block</div>