Javascript Course


Defining a class

To define a class in JavaScript, you can use directly the clss declaration with the name of the class.


class className {
 constructor(params){
 //properties
 }

 //methods
}

- Another way, assign the class to a variable:
let varClass = class {
 constructor(params){
 //properties
 }

 //methods
}
The diference is that "varClass" is a variable, so its value can be changed.

- "params" represents the arguments that will be passed when an object instance of the class is created (with the new) keyword.
let obj = new className(arguments);

//Or
let ob2 = new varClasa(arguments);

Properties and Methods of the class

Properties are defined in the constructor(), with the this keyword.
constructor() is a special method that is automatically executed when an object of the class is created (with the new keyword).
Inside the class body, the properties and methods are called by using the this keyword (the class-name for static methods).
Outside the class, the properties and methods can be called using the object name (the class-name for static methods).


- Example of a simple JavaScript class:
<div id='ex_res'>Here we show the results.</div>

<script>
class Rectangle {
 //receives two arguments when an object of the class is created
 constructor(width, height){
 //set properties
 this.width = width;
 this.height = height;
 }

 //a simple method, it uses the properties defined in constructor
 area(){
 return this.width * this.height;
 }

 //another method (receives one argument); to see how to call a method in other method
 multipliArea(n){
 return this.area() *n;
 }
}

//usage, create an object of the class; using the new keyword
let ob_rect = new Rectangle(5, 3);

//gets values from the area() and multipliArea() methods
var area = ob_rect.area();
var m_area = ob_rect.multipliArea(3);

//add in the #ex_res html element the values of area and m_area
document.getElementById('ex_res').innerHTML ='area() method returned: '+ area +'<br>multipliArea(3) returned: '+ m_area;
</script>

Static Methods

The static methods inside the class are created with the static keyword.
Inside and Outside the class body, the static methods are called with the name of the class.

A static method cannot be called with the "this" keyword or through a class instance.


- Example:
<div id='ex2_res'>Here we show results.</div>

<script>
class User {
 //receives user name when an object of the class is created
 constructor(user){
 //set property
 this.user = user;
 }

 //static method
 static Hello(name){
 return 'Hello '+ name;
 }

 //basic method, to see how to call a static method inside other method
 titleHello(){
 var re = User.Hello(this.user);
 return '<h2>'+ re +'</h2>';
 }
}

//usage, create an object of the class
let ob_usr = new User('MarPlo');

//add in the #ex2_res html element the value returned by titleHello()
document.getElementById('ex2_res').innerHTML = ob_usr.titleHello();

//get the result from the static method (with the class name)
var hello = User.Hello('Peace');
alert(hello);
</script>

Multiple instances of a class

You can create and use multiple objects instances of the same class, with different values.

- Example:
<div id='ex_hi1'>#ex_hi1 div</div>
<div id='ex_hi2'>#ex_hi2 div</div>

<script>
class Test {
 constructor(name){
 this.name = name;
 }

 //adds 'Helo name' in the #id HTML element 
 addHello(id){
 document.getElementById(id).innerHTML ='<h3>Hello '+ this.name +'</h3>';
 }
}

//first object instance
let ob1 = new Test('Happines');
ob1.addHello('ex_hi1'); //calls the method with the ID of a Div

//second instance
let ob2 = new Test('Peace');
var hi2 = ob2.addHello('ex_hi2'); //calls the method with other ID
</script>

Getter and Setter class methods

The getter/setter syntax exists for properties that must be calculated based on conditions or other properties.
The getter methos is defined with the get keyword.
The setter methos is defined with the set keyword.
The getter and setter must have the same name.
The setter must have an argument. It is automatically called when a value is assigned to a property with the same name as setter; that value is passed for argument.


- You can understand from the code in this example:
<div id='ex3_res'>Here we show results.</div>

<script>
class Article {
 constructor(){
 this.th1 ='No title';
 }

 //getter, returns the th1 property that is defined in setter
 get title(){
 return this.th1;
 }

 //setter, it is called when a value (val) is assigned to the title property
 set title(val){
 if(val !='') this.th1 ='<h1>'+ val +'</h1>';
 }
}

//usage, create an object of the class
let ob_art = new Article();

//assigns a value to title property
//this code will automatically call the setter: title() with the value as argument
ob_art.title ='CoursesWeb.net - JS Classes';


//this code will automatically call the getter: title()
var th1 = ob_art.title;

//add in the #ex3_res html element the value of th1
document.getElementById('ex3_res').innerHTML = th1;
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Define and Use Classes in JavaScript

Last accessed pages

  1. PHP getElementById and getElementsByTagName (49471)
  2. Mysql SELECT JOIN tables on two different Databases (4498)
  3. jQuery UI draggable - Drag elements (11448)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142520)
  5. Using the Bone Tool (4253)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (62)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)