Created
November 3, 2012 21:27
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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