Javascript - Prototype Chaining

Prototype - Examplo de Encadeamento

by Angelo Rogério Rubin

HTML

<h2 id="result"><h2>

CSS

h2 {
    font-family: Verdana;
    float: left;
    margin: 0;
    padding: 0;
}

JavaScript

// Funções Construtoras
function Shape(){
    this.name = 'shape';
    this.toString = function() {
        return this.name;
    };
}

function TwoDShape(){
    this.name = '2D shape';
}

function Triangle(side, height) {
    this.name = 'Triangle';
    this.side = side;
    this.height = height;
    this.getArea = function(){
        return this.side * this.height / 2;
    };
}

// Instâncias
TwoDShape.prototype = new Shape();
Triangle.prototype = new TwoDShape();

// Evitando problemas com o construtor
TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype.constructor = Triangle;

var my = new Triangle(5, 100);

var r = document.getElementById('result');
// r.innerHTML = my.getArea();
// r.innerHTML = my.toString();
// r.innerHTML = my.constructor;
// r.innerHTML = my instanceof Shape;
// r.innerHTML = Shape.prototype.isPrototypeOf(my);

var td = new TwoDShape();
// r.innerHTML = td.toString();

function Shape(){}
// augment prototype
Shape.prototype.name = 'shape';
Shape.prototype.toString = function() {
    return this.name;
};

function TwoDShape(){}
// cuidar da herança
TwoDShape.prototype = new Shape();
TwoDShape.prototype.constructor = TwoDShape;
// augment prototype
TwoDShape.prototype.name = '2D shape';

function Triangle(side, height) {
    this.side = side;
    this.height = height;
}
// cuidar da herança
Triangle.prototype = new TwoDShape();
Triangle.prototype.constructor = Triangle;
// augment prototype
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){
    return this.side * this.height / 2;
};

var my = new Triangle(5, 15);
// r.innerHTML = my.getArea();

r.innerHTML = my.hasOwnProperty('name');