Created
October 18, 2015 11:54
-
-
Save pawelqbera/578e1d354586656e08c7 to your computer and use it in GitHub Desktop.
Prototypal Inheritance in Object Oriented JavaScript
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
/** | |
* Protypal Inheritance in JavaScript | |
* - uses prototypal pattern | |
*/ | |
// Helpers and polyfills | |
/** | |
* Creates instantiation taking an object of newly | |
* defined properties as a parameter | |
* @param {object} [values] Additional properties of | |
* a new instance | |
*/ | |
function create(values) { | |
var instance = Object.create(this); | |
Object.keys(values).forEach(function(key){ | |
instance.key = values[key]; | |
}); | |
return instance; | |
} | |
/** | |
* Polyfill for Object.create() | |
*/ | |
if ( typeof Object.create !== 'function' ) { | |
Object.create = function(o, props) { | |
function F() {} | |
F.prototype = o; | |
result = new F(); | |
if ( typeof(props) === "object" ) { | |
for (var prop in props) { | |
if (props.hasOwnProperty((prop))) { | |
result[prop] = props[prop].value; | |
} | |
} | |
} | |
return result; | |
}; | |
} | |
// SuperClass | |
var orb = { | |
create: function(values) { | |
var instance = Object.create(this); | |
Object.keys(values).forEach(function(key){ | |
instance[key] = values[key]; | |
}); | |
return instance; | |
}, | |
spin: function() { | |
console.log(this.name + ' is spinning around!'); | |
}, | |
circle: function() { | |
console.log(this.name + ' is circling around the Sun!'); | |
} | |
}; | |
// Planet Class | |
var planet = Object.create(orb); | |
// Moon Class | |
var moon = planet.create({ | |
circle: function() { | |
console.log(this.name + ' is circling around the ' + this.planetName); | |
} | |
}); | |
// Usage | |
var earth = planet.create({ | |
name: "Earth" | |
}); | |
var earthMoon = moon.create({ | |
name: "Moon", | |
planetName: earth.name | |
}); | |
earth.spin(); | |
earth.circle(); | |
earthMoon.spin(); | |
earthMoon.circle(); | |
var saturn = planet.create({ | |
name:"Saturn", | |
}); | |
var titan = moon.create({ | |
name: "Titan", | |
planetName: saturn.name | |
}); | |
titan.spin(); | |
titan.circle(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment