Skip to content

Instantly share code, notes, and snippets.

@looselytyped
Created November 3, 2012 21:27
Show Gist options
  • Save looselytyped/4008901 to your computer and use it in GitHub Desktop.
Save looselytyped/4008901 to your computer and use it in GitHub Desktop.
A set of JavaScript examples to explore prototypal inheritance. Use the Chrome/Safari Developer Tools console to run
clear();
var assert = function(bool, msg) {
if(!bool) {
console.error("INVALID: " + (msg ? msg : ''));
}
}
////////////////////////////////////////////////////////
clear();
function Person(name) {
this.name = name;
}
console.log(Person.prototype); // Person { ... }
console.log(Person.prototype.__proto__); // Object { ... }
console.log(Person.prototype.__proto__.__proto__); // null
////////////////////////////////////////////////////////
clear();
var person = {
name: "raju"
}
console.log(person.__proto__); // Object { ... }
console.log(person.__proto__.__proto__); // null
////////////////////////////////////////////////////////
clear();
function Person(name) {
this.name = name;
}
var person = new Person("raju");
console.log(person.__proto__); // Person { ... }
console.log(person.__proto__.__proto__); // Object { ... }
console.log(person.__proto__.__proto__.__proto__); // null
////////////////////////////////////////////////////////
clear();
function Person(name) {
this.name = name;
}
var person = new Person("raju");
Person.prototype.sayHello = function() {
return "Hello " + this. name;
}
person.sayHello();
////////////////////////////////////////////////////////
clear();
function Person(name) {
this.name = name;
}
function Mammal() {}
Mammal.prototype.nurture = function() { return "Care"; }
Person.prototype.__proto__ = Mammal.prototype;
var person = new Person("raju"); // create an instance
console.log(person.__proto__); // Person { ... }
console.log(person.__proto__.__proto__); // Object { ... }
console.log(person.__proto__.__proto__.__proto__); // null
person.nurture();
////////////////////////////////////////////////////////
clear();
Array.prototype.map = function(app) {
var ret = [];
for(var i = 0; i < this.length; i++) {
ret.push(app(this[i]));
}
return ret;
}
function multiplyByTwo(n) {
return n * 2;
}
var arr = [1,2,3];
arr.map(multiplyByTwo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment