Playing with classes and objects in Javascript
So, let’s play a little bit with classes and objects in Javascript. If you come from the class based languages like Java and C++, the way we handle classes in javascript looks a little bit strange. First, javascript is not class based, so, it doesn’t have the entity class. A class in javascript is a function. So we can see a simple class in the example below:
MyClass = function(){
};
var instance = new MyClass();
So, to create a new class in javascript we only need to define a new function.
As we know, class has attributes. We couldĀ add attributes to our class this way:
MyClass = function(){
this.attribute = 'Hello';
}
var instance = new MyClass();
alert(instance.attribute);
So, it is not too different as we have on other languages.
We also could pass parameters in the constructor , so we can initialize the class attributes.
MyClass = function(attrValue){
this.attribute = attrValue;
}
var instance = new MyClass("Hello Class");
alert(instance.attribute);
We can do the same forĀ functions on our class:
MyClass = function(attrValue){
this.attribute = attrValue;
this.classFunction = function (){alert('Class function')};
}
var instance = new MyClass("Hello Class");
alert(instance.attribute);
instance.classFunction();
Let’s us create a new class called Person. It should have two attributes: name and age, and a function toString that should display its attributes values. The code will be like this:
var Person = function(){
this.name = '';
this.age = '';
this.toString = function(){
return "Name:"+ this.name + " - Age:" + this.age;
};
}
var onePerson = new Person();
onePerson.name = 'Junior';
onePerson.age = '23';
alert(onePerson.toString());
This was a simple introduction for classes on Javascript.
See you in the next post.