Changing the Prototype Retroactively Changes Other Objects

for CSCI E3, Harvard University author(s): Larry Bouthillier

by DustyWhite

HTML

<div>
    <p>Changing the constructor's prototype affects every object that's ever been created using that constructor. </p><p>
    Notice how in line 14, the call to spiderman.getFullName() fails since there's no method with that name in the spiderman object, or in the Person object. But when I make the same call on line 25, it works.  Adding getFullName() to the Person.prototype object means that it's available to every object I create from Person, in the past or the future. 
    </p>
    <p>We use the try/catch block on lines 13-17 to handle the 'undefined is not a function' error that would break our code on line 14. More on try/catch on <a href="http://www.w3schools.com/jsref/jsref_try_catch.asp" target="_blank">W3Schools</a> or <a href="http://javascript.info/tutorial/exceptions" target="_blank">JavascriptInfo</a>. </p>
    <p>Output will appear below:</p>
</div>
<div id="output"></div>
<p></p>

CSS

#output{
    width:80%;
    border: 1px solid black;
    padding: 1em;
}

JavaScript

// our Person constructor
function Person(fname, lname) {
    this.fname = fname;
    this.lname = lname;
}

// Now we'll make a new object - spiderman - based on our Person
var spiderman = new Person("Peter","Parker");

/* Here we'll try to access getFullName() on spiderman. It fails,
 since there's no such property on a Person. 
 */
try{
    spiderman.getFullName();  // undefined
} catch(e){
    logMessage("Line 16: We've caught an error: " + e );   
}

// Now we create a getFullName() method on the Person prototype 
 Person.prototype.getFullName = function(){
	return this.fname + " " +  this.lname;
} 

// and try calling getFullName() again, on our pre-existing spiderman 
 logMessage("Line 25: Now it works: "+spiderman.getFullName()); 



// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id){
    if (!id){
        id="output";
    }
    document.getElementById(id).innerHTML += msg + "<br>";
}