Home  • Programming • JavaScript

JavaScript and Object Oriented Programming (OOP)

Terminology

Class Defines the characteristics of the Object. Object An Instance of a Class. Property An Object characteristic, such as color. Method An Object capability, such as walk. Constructor A method called at the moment of instantiation. Inheritance A Class can inherit characteristics from another Class. Encapsulation A Class defines only the characteristics of the Object, a method defines only how the method executes. Abstraction The conjunction of complex inheritance, methods, properties of an Object must be able to simulate a reality model. Polymorphism Different Classes might define the same method or property.

JavaScript Core Objects

JavaScript has several objects included in its core; for example, there are objects like Math, Object, Array, and String. Example The example below shows how to use the Math object to get a random number by using its random() method
 alert(Math.random());

JavaScript Custom Objects

The class
function Person() { }
The Object (Class Instance) There are several ways to create objects in JavaScript, and all of them have their place. To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later. In the example below we define a class named Person and we create two instances (person1 and person2).
function Person() { }
var person1 = new Person();
var person2 = new Person();
Creating objects using new Object() The simplest way is to use the new operator, specifically, new Object():
<script language="javascript" type="text/javascript">
<!--

person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"

person.run = function() {
	this.state = "running"
	this.speed = "4ms^-1"
}

//-->
</script>
We define a custom object "person," then add to it its own properties and method afterwards. In this case, the custom method merely initializes two more properties. Creating objects using Literal Notation Another inline way of defining an object is via literal notation. Supported in JavaScript1.2 and above, it's a more robust form of creating an object on the fly:
<script language="javascript" type="text/javascript">
<!--

// Object Literals

timObject = {
	property1 : "Hello",
	property2 : "MmmMMm",
	property3 : ["mmm", 2, 3, 6, "kkk"],
	method1 : function(){alert("Method had been called" + this.property1)}
};

timObject.method1();
alert(timObject.property3[2]) // will yield 3

var circle = { x : 0, y : 0, radius: 2 } // another example

// nesting is no problem.
var rectangle = { 
	upperLeft : { x : 2, y : 2 },
	lowerRight : { x : 4, y : 4}
}

alert(rectangle.upperLeft.x) // will yield 2

//-->
</script>
Literal notion can contain arrays or arbitrary JavaScript expressions or values. The Property (object attribute) Properties are variables contained in the class; every instance of the object has those properties. Working with properties from within the class is done by the keyword this, which refers to the current object. In the example below we define the gender property for the Person class and we define it at instantiation.
function Person(gender) {
  this.gender = gender;
  alert('Person instantiated');
}

var person1 = new Person('Male');
var person2 = new Person('Female');

//display the person1 gender
alert('person1 is a ' + person1.gender); // person1 is a Male
The methods Methods follow the same logic as properties; the difference is that they are functions and they are defined as functions. Calling a method is similar to accessing a property, but you add () at the end of the method name, possibly with arguments. To define a method, assign a function to a named property of the class's prototype property; the name that the function is assigned to is the name that the method is called by on the object. In the example below we define and use the method sayHello() for the Person class.
function Person(gender) {
  this.gender = gender;
  alert('Person instantiated');
}

Person.prototype.sayHello = function()
{
  alert ('hello');
};

var person1 = new Person('Male');
var person2 = new Person('Female');

// call the Person sayHello method.
person1.sayHello(); // hello

JavaScript Inheritance

Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single class inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance. In the example below, we define the class Student as a child class of Person. Then we redefine the sayHello() method and add the sayGoodBye() method.
// define the Person Class
function Person() {}

Person.prototype.walk = function(){
  alert ('I am walking!');
};
Person.prototype.sayHello = function(){
  alert ('hello');
};

// define the Student class
function Student() {
  // Call the parent constructor
  Person.call(this);
};

// inherit Person
Student.prototype = new Person();

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
 
// replace the sayHello method
Student.prototype.sayHello = function(){
  alert('hi, I am a student');
};

// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
  alert('goodBye');
};

var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();

// check inheritance
alert(student1 instanceof Person); // true 
alert(student1 instanceof Student); // true
Using Object.create the inheritance line would instead be:
Student.prototype = Object.create(Person.prototype);

JavaScript Encapsulation

In the previous example, Student does not need to know how the Person class's walk() method is implemented, but still can use that method; the Student class doesn't need to explicitly define that method unless we want to change it. This is called encapsulation, by which every class inherits the methods of its parent and only needs to define things it wishes to change.

JavaScript Abstraction

Abstraction is a mechanism that permits modeling the current part of the working problem. This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects. The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model). and the Function.prototype property is an instance of Object (this demonstrates composition)
var foo = function(){};
alert( 'foo is a Function: ' + (foo instanceof Function) );
alert( 'foo.prototype is an Object: ' + (foo.prototype instanceof Object) );

Polymorphism

Just like all methods and properties are defined inside the prototype property, different classes can define methods with the same name; methods are scoped to the class in which they're defined. This is only true when the two classes do not hold a parent-child relation (when one does not inherit from the other in a chain of inheritance).

Comments 2


nice
<?php
 class Student{

      private $id;
      private $name;
      private $level;
   
   function Student($id,$n,$l){
   
     $this->id=$id;
	 $this->name=$n;
	 $this->level=$l;
   }
   public function setId($id){
      $this->id=$id;
   }
   public function getId(){
      return $this->id;
   }
   public function setName($n){
      $this->name=$n;
   }
   public function getName(){
      return $this->name;
   }
   public function setLevel($l){
      $this->level=$l;
   }
   public function getLevel(){
      return $this->level;
   }
 }
 
  //------
  $obj=new Student("1122","Meda","Higher");
  $obj1=new Student("1133","Billal","Higher");
  $obj2=new Student("1144","Hossain","Higher");
  $obj3=new Student("1155","Vai","Higher");
  
 //--------
 
 $students=array($obj,$obj1,$obj2,$obj3);
 
   $id=1144;
   
 foreach($students as $student){
 
   if($id==$student->getId()){
      echo "ID :". $student->getId(),"<br/>"; 
      echo "Name :".$student->getName(),"<br/>";
	  echo "Level :".$student->getLevel();
   }
 } 

?>
Copyright © 2024. Powered by Intellect Software Ltd