Skip to content

Instantly share code, notes, and snippets.

@gokulkrishh
Created April 9, 2015 11:58
Show Gist options
  • Save gokulkrishh/1487f06b5e671bae9c3e to your computer and use it in GitHub Desktop.
Save gokulkrishh/1487f06b5e671bae9c3e to your computer and use it in GitHub Desktop.
Simple Inheritance in JS // source http://jsbin.com/botoqozude
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Inheritance in JS</title>
</head>
<body>
<script id="jsbin-javascript">
//Class A
function classA() {
this.name = 'I am from class A';
}
//Create a print method in class A
classA.prototype.print = function () {
console.log(this.name);
};
//Creating constructor
var a = new classA();
a.print();//print name
//Class B
function classB() {
this.name = 'I am from class B';
}
//inherit child methods from parent method
var inheritFrom = function (child, parent) {
child.prototype = Object.create(parent.prototype);
};
inheritFrom(classB, classA); //copy classA methods in prototype to classB prototype
//Creating constructor
var b = new classB();
b.print();//print name
</script>
<script id="jsbin-source-javascript" type="text/javascript">//Class A
function classA() {
this.name = 'I am from class A';
}
//Create a print method in class A
classA.prototype.print = function () {
console.log(this.name);
};
//Creating constructor
var a = new classA();
a.print();//print name
//Class B
function classB() {
this.name = 'I am from class B';
}
//inherit child methods from parent method
var inheritFrom = function (child, parent) {
child.prototype = Object.create(parent.prototype);
};
inheritFrom(classB, classA); //copy classA methods in prototype to classB prototype
//Creating constructor
var b = new classB();
b.print();//print name</script></body>
</html>
//Class A
function classA() {
this.name = 'I am from class A';
}
//Create a print method in class A
classA.prototype.print = function () {
console.log(this.name);
};
//Creating constructor
var a = new classA();
a.print();//print name
//Class B
function classB() {
this.name = 'I am from class B';
}
//inherit child methods from parent method
var inheritFrom = function (child, parent) {
child.prototype = Object.create(parent.prototype);
};
inheritFrom(classB, classA); //copy classA methods in prototype to classB prototype
//Creating constructor
var b = new classB();
b.print();//print name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment