Small javascript classes introduction

No class keyword:

In javascript there is no Class keyword. Classes are defined with the function keyword. A class Person is defined as follow:

	function Person() { }

The this keyword:

For defining properties and methods in class the this keyword is used, like this:

	function Person() {
		this.name;
		this.birthday;
		this.getAge = function(currentYear){
			var birthYear = this.birthday.getFullYear;
			return (currentYear - birthYear);
		}
	 }

Create objects:

To instantiate the object, set the property's and call the method, like this:

	var myPerson = new Person();
	myPerson.birthday = new date("July 21, 1983");
	alert(myPerson.getAge(2014));

The prompt is obviously going to show you the number 31 ( 2014 - 1983).

Constructors:

Using a constructor for you class is as easy as define some parameters:

	function Person(personName, personBirthday) {
		this.name = personName ;
		this.birthday = personBirthday) ;
		this.getAge = function(){
			var birthYear = this.birthday.getFullYear;
			return (currentYear - birthYear);
		}
	}

Singleton object:

With the person class from the example you can create different objects of the type person. But what if you want just one class: person. You want a singleton object. Then you have to define your class as follow:

	var MyPerson = function Person() {
		this.name = personName ;
		this.birthday = personBirthday) ;
		this.getAge = function(currentYear){
			var birthYear = this.birthday.getFullYear;
			return (currentYear - birthYear);
		}
	}

Now it is a singleton class wich means you can use the properties and methods of the MyPerson object right away:

	MyPerson.birthday = new date("July 21, 1968");
	alert(MyPerson.getAge(2014));

This will going to prompt you with 46, well and that is OLD.

 

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!