Overwriting Prototype Properties

prototype properties are read only. If you try to set them you will set the property on the instance which points to the prototype and not the prototype itself.

by sym3tri

HTML

<html>
    <body>
        <div id="out"></div>
    </body>
</html>

JavaScript

function print(txt) {
    var outDiv = $('#out');
    outDiv.html(outDiv.html() + '<br/><br/>' + txt);
}

$(document).ready(function() {

    var Foo = function() {
        this.foo = 'flam';
    }
    
    var Bar = function() { 
        this.bar = 'bam';
    }
    
    Bar.prototype = { ho: 'humm', fi: 'fo' };
    
    var x = new Bar();
    
    // exists and is own
    print(x.bar);
    print(x.hasOwnProperty('bar'));

    // exists not own, from prototype
    print(x.ho);
    print(x.hasOwnProperty('ho'));
    
    // set ho which only exists on prototype
    x.ho = 'dee';
    
    // now check value of ho
    // surprisingly ho is now on the instance x, not the prototype.
    // the ho property exists on both now
    print(x.ho);
    print(x.hasOwnProperty('ho'));
    
});