Skip to content

Instantly share code, notes, and snippets.

@nulltask
Created February 15, 2012 13:08
Show Gist options
  • Select an option

  • Save nulltask/1835585 to your computer and use it in GitHub Desktop.

Select an option

Save nulltask/1835585 to your computer and use it in GitHub Desktop.
Prototype inheritance example
/**
* Super class constructor.
*/
function Animal() {
this.type = 'animal';
}
/**
* Set `Animal` prototype methods.
*/
!function(proto) {
/**
* Define private method.
*/
function pseudoPrivateFn() {
console.log('name: %s', this.name);
}
/**
* Define public method.
*/
proto.superPublicFn = function() {
console.log('I am superPublicFn.');
pseudoPrivateFn.call(this);
};
}(Animal.prototype);
/**
* Subclass constructor.
*/
function Human() {
Animal.apply(this, arguments);
this.name = 'John Doe';
}
/**
* Inherits from `Animal`
*/
Human.prototype = new Animal();
/**
* Set `Human` prototype methods.
*/
!function(proto) {
/**
* Define private method.
*/
function pseudoPrivateFn1() {
console.log(Object.prototype.toString.call(this));
console.log("type: %s", this.type);
}
/**
* Define private method.
*/
function pseudoPrivateFn2() {
console.log("name: %s", this.name);
console.log("age: %s", this.age);
console.log("protoValue: %s", proto.protoValue);
}
/**
* Define public method.
*/
proto.subPublicFn1 = function() {
console.log("I am subPublicFn1,");
pseudoPrivateFn1();
pseudoPrivateFn1.call(this);
};
/**
* Define public method.
*/
proto.subPublicFn2 = function() {
console.log("I am subPublicFn2.");
pseudoPrivateFn2();
console.log("My name is %s!", this.name);
pseudoPrivateFn2.call(this);
};
proto.protoValue = 100;
}(Human.prototype);
/**
* Usage.
*/
var human = new Human();
human.superPublicFn();
human.subPublicFn1();
human.subPublicFn2();
human.age = 25;
human.subPublicFn2();
I am superPublicFn.
name: John Doe
I am subPublicFn1,
[object global]
type: undefined
[object Object]
type: animal
I am subPublicFn2.
name: undefined
age: undefined
protoValue: 100
My name is John Doe!
name: John Doe
age: undefined
protoValue: 100
I am subPublicFn2.
name: undefined
age: undefined
protoValue: 100
My name is John Doe!
name: John Doe
age: 25
protoValue: 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment