Last active
December 14, 2015 11:39
-
-
Save keriati/5080691 to your computer and use it in GitHub Desktop.
Prototypal Inheritance in 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
<!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