Skip to content

Instantly share code, notes, and snippets.

@makenova
Created May 9, 2014 00:00
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 makenova/4cfeb617bb2ad3990c02 to your computer and use it in GitHub Desktop.
Save makenova/4cfeb617bb2ad3990c02 to your computer and use it in GitHub Desktop.
Notes on the JavaScript prototype chain

Adding methods on the Constructor vs the prototype

Adding a method on the constructor will duplicate that method for every instance of the object that created, consuming memory but also granting the method access private variables on the object. Adding a method on the prototype will will not duplicate it for new instances, conserving memory while leaving it available to all instances.

// Constructor with greet method directly on it.
var Person = function (name, age) {
	this.name = name;
	this.age = age;
	var secret = "I'm super happy";
	this.greet = function (name) {
		return 'Hello ' + name + ' my name is ' + this.name + ' and ' + secret;
	};
};

// Constructor with greet method on the prototype
var oPerson = function (name, age) {
	this.name = name;
	this.age = age;
	var secret = "I'm super happy";
};

oPerson.prototype.greet = function (name) {
	return 'Hello ' + name + ' my name is ' + this.name;
};

var adrian = new Person('Adrian', 24);
var jason = new oPerson('Jason', 26);

console.log(adrian.greet('John'));
console.log(jason.greet('Tommy'));
// Can I create an object whose constructor has properties but only
// change the properties for a single instance of the object?
var Polygon = function (sides) {
this.sides = sides;
}
Polygon.prototype.perimiter = function (lengthOfSides) {
return lengthOfSides * this.sides;
}
// Property to be tested
Polygon.prototype.exprop = 100;
// Instance objects
var square = new Polygon(4);
var triangel = new Polygon(3);
// Test that objects work as expected
console.log(square.perimiter(2), triangel.perimiter(2));
// Check object
console.log(square, triangel);
// make changes to square instance object
square.exprop -= 50;
// Does the change to the square instance affect the triangle instance?
console.log(square.exprop, triangel.exprop);
// Nope!! When the prototype property is changed for an instance, the
// changed property is copied to that instance.
console.log(square, triangel);
// Show that exprop property doesn't exist on Polygon instance object triangle.
console.log('triangle has exprop property: ', triangel.hasOwnProperty('exprop'));
console.log('square has exprop property: ', square.hasOwnProperty('exprop'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment