Skip to content

Instantly share code, notes, and snippets.

@wulfgarpro
Created December 11, 2012 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wulfgarpro/4257841 to your computer and use it in GitHub Desktop.
Save wulfgarpro/4257841 to your computer and use it in GitHub Desktop.
Javascript prototypes, constructors, and inheritence
​var Person = function(name) {
if(name) this.name = name;
};
Person.prototype.name = 'No name';
Person.prototype.setName = function(name) {
this.name = name;
};
Person.prototype.getName = function() {
return this.name;
};
console.log(Person.prototype.name === 'No name'); // true
var me = new Person('James');
console.log(me.constructor === Person); // true
console.log(me.name === 'James'); // true
var you = new Person();
console.log(you.name === Person.prototype.name);​​ // true
var Father = function(children) {
if(children) this.children = children;
};
​Father.prototype = new Person(); // inheritence
​var dad = new Father(1)​;
for(var prop in dad) {console.log(prop);} // name, children, setName, getName
​dad.setName('Garry');
console.log(dad.getName());​ // Garry​​​​
@benpetito
Copy link

Father.prototype = new Person();
That is the most confusing part of all that.

@wulfgarpro
Copy link
Author

The way I understand it:

  • Every constructor (JavaScript function, which is also an object) has a prototype property (object) that you can add properties to:
Person.prototype.name = "";
  • A prototype is a JavaScript object, that can be overwritten:

    var Person = function(name) { ... }; Person.prototype = {};
  • Person is a constructor

  • An instance of Person is given a prototype property (which you can't nominally access) with a reference to the Person constructor in memory, where it's prototype property is accessible:

var me = new Person(); me.constructor.prototype === Person.prototype;
  • Father is also a constructor
  • Father's prototype property is set to an instance of a Person, therefore we have a prototype chain:
var dad = new Father(); dad.constructor.prototype.constructor.prototype=== Person.prototype;

How the internal prototype property works with delegation and all is beyond me. I just know that the above property chain checks provide proof that Father is indeed a sub class of Person.

@wulfgarpro
Copy link
Author

Reading some more:

  • A constructor's constructor property is a property of it's prototype object pointing back at the constructor object
  • So, in the above when we say "dad.constructor.prototype.constructor.prototype", we're actually using the built in delegation pointing back to the Father constructor's prototype property, which is indeed an instance of Person, delegating to the Person constructor object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment