View Full Version : i'm frying my noodle with prototypal inheritance!!

07-30-2010, 10:18 PM
please bear with my noobishness, but i've been trying for many hours to understand what is going on behind this code:


function Person() {
document.write('constructor: <br/>'+this.constructor); //displays Person constructor
this.name = "Rob Roberson";
this.age = 31;

function Employee() {
document.write('<br/>constructor: <br/>'+this.constructor); //displays Person constructor
this.dept = "HR";
this.manager = "John Johnson";

Employee.prototype = new Person();

var Ken = new Employee();

document.write('<br/>'+Ken.constructor); //displays Person constructor
document.write('<br/>name:'+ Ken.name + '<br/>age:' + Ken.age + '<br/>dept:' + Ken.dept + '<br/>manager:' + Ken.manager ); //displays all properties correctly


from what i've read, every object references a prototype. in this case, the Employee function will automatically reference a prototype with 'constructor' as its initial value. this command:

Employee.prototype = new Person();

will replace the Employee function's prototype to an instance of Person. so now Employee function's prototype will contain both name and age properties, BUT, and this is where i get lost, ITS CONSTRUCTOR PROPERTY GETS REPLACED! so how does:

var Ken = new Employee();

actually construct an instance of Employee if the reference to its constructor has been replaced by an instance of Person that only contains name and age properties? how is Ken ever initialized by Employee constructor?

08-04-2010, 02:05 AM
usually the word prototype is used to write methods or "functions" that belong to the base object.

if you say

function Truck(){
this.frontTires = 2;
this.backTires = 2;

then you would use the prototype to add more methods to the truckobject and call them when you need them. some trucks have 4 back tires, so you could say...

Truck.prototype.BiggerTruck = function(){
return this.backTires += 2;

then you would create a new instance of Truck, you don't know what size it is or how many tires it has, you just know it is a truck. So you say...

var dumpTruck = new Truck();

Even though the variable we just created says dumpTruck, we only created a simple Truck object, so now you can tell truck that you want to access the BiggerTruck method of the object Truck like this

dumpTruck.BiggerTruck ()