Skip to content

Instantly share code, notes, and snippets.

@keriati
Last active December 14, 2015 11:39
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 keriati/5080691 to your computer and use it in GitHub Desktop.
Save keriati/5080691 to your computer and use it in GitHub Desktop.
Prototypal Inheritance in JavaScript
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
if (typeof Object.create === 'undefined') {
Object.create = function (o) {
function F() {};
F.prototype = o;
return new F();
};
}
(function(){
var NameSpace = {};
// Person constructor function
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Person prototype
Person.prototype = {
getFullName : function() {
return this.firstName + " " + this.lastName;
}
};
NameSpace.Person = Person;
// Employee inherits from Person
function Employee(firstName, lastName, position) {
// Call parent constructor
Person.call(this, firstName, lastName);
this.position = position;
}
// Employee prototype extend parents prototype
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.getId = function() {
return this.getFullName() + ", " + this.position;
};
NameSpace.Employee = Employee;
window.NameSpace = NameSpace;
})();
var john = new NameSpace.Person("John", "Doe");
console.log(john.getFullName());
var jack = new NameSpace.Employee("Jack", "Doe", "Manager");
console.log(jack.getFullName());
console.log(jack.getId());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment