Skip to content

Instantly share code, notes, and snippets.

@prasadshir
Created September 1, 2013 11:42
Show Gist options
  • Save prasadshir/6403933 to your computer and use it in GitHub Desktop.
Save prasadshir/6403933 to your computer and use it in GitHub Desktop.
Object Oriented JS Simple Example
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>Object Oriented JS - Work with Console!</div>
<script>
/**
* JavaScript is a prototype-based language which contains no class statement
* JavaScript uses functions as classes.
* Defining a class is as easy as defining a function.
* In the example below we define a new class called Person.
**/
function Person(myname, gender, age){
this.name = myname;
this.gender = gender;
this.age = age;
};
/*
* Methods or Member functions are added in the 'propotype' property
* of the class
*/
Person.prototype = {
getName: function(){
console.log(this.name);
},
getGender: function(){
console.log(this.gender);
}
};
Person.prototype.getAge = function(){
console.log(this.age);
}
/*
* instance of a class is created with 'new' keyword
* class methods can be called on the instance using a .methodName()
*/
var p1 = new Person("Prasad","Male",20);
p1.getName()
/**
* Inheritance - child classes can be created by simply calling a
* Parent class in the contructor function
*/
function Student(name, gender, age, school){
//call parent constructor
Person.call(this, name, gender, age);
this.school = school;
}
// inherit Person
Student.prototype = new Person();
//correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
Student.prototype.getSchool = function(){
console.log(this.school);
return this.school;
}
var s1 = new Student("Shaunak","M",8,"Gurukul" );
s1.getName();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment