Classes are a template for creating objects. They encapsulate data with code to work on that data. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError.
/*
* Classes are a template for creating objects. They encapsulate data with code to work on that data
* Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
*/
class User{
//private fields are declared with #
#name;
#dob;
#type;
static USER_TYPE = "USER_TYPE";
static ADMIN_TYPE = "ADMIN_TYPE";
/*
* The constructor method is a special method:
* It has to have the exact name "constructor"
* It is executed automatically when a new object is created
* It is used to initialize object properties
* It if you do not define a constructor method, JavaScript will add an empty constructor method.
*/
constructor(name, dob, type) {
this.name = name;
this.dob = dob;
if(type==undefined){
this.type = User.USER_TYPE;
}else{
this.type = type;
}
}
getAge(date){
return date.getFullYear() - this.dob.getFullYear();
}
getDob(){
return this.dob;
}
static getAgeDifference(user1, user2){
return user1.getDob().getFullYear() - user2.getDob().getFullYear();
}
}
let folau = new User("Folau",new Date(1986, 12, 03));
console.log("Folau: ", folau);
console.log("Folau age: ", folau.getAge(new Date()));
let lisa = new User("Lisa",new Date(1987, 04, 12));
console.log("Lisa: ", lisa);
let ageDifference = User.getAgeDifference(folau, lisa);
console.log("ageDifference: ", ageDifference);
Private instance fields and methods are declared with # names (pronounced “hash names“), which are identifiers prefixed with #. The # is a part of the name itself. It is used for declaration and accessing as well.
#name; #dob; #type;
The static keyword defines static methods and variabls for classes.
Static methods and variables are called directly on the class(using the Class name) – without creating an instance/object of the class.
static USER_TYPE = "USER_TYPE";
static ADMIN_TYPE = "ADMIN_TYPE";
static getAgeDifference(user1, user2){
return user1.getDob().getFullYear() - user2.getDob().getFullYear();
}
The extends keyword is used to create a child class of another class (parent). The child class inherits all the methods from another class. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.
Note: From the example above; The super() method refers to the parent class. By calling the super() method in the constructor method, we call the parent’s constructor method and gets access to the parent’s properties and methods.
class Member extends User{
id;
constructor(id, name, dob, type) {
super(name, dob, type);
this.id = id;
}
getId(){
return this.id;
}
getNext5yearAge(){
let dob = super.getDob();
let today = new Date();
return (today.getFullYear() - dob.getFullYear()) + 5;;
}
}
let laulau = new Member(100, "Laulau",new Date(1986, 12, 03));
console.log("laulau: ", laulau);
/*
dob: Sat Jan 03 1987 00:00:00 GMT-0700 (Mountain Standard Time) {}
id: 100
name: "Laulau"
type: "USER_TYPE"
*/
laulau.id = 250;
console.log("laulau id: ", laulau.getId());// 250
console.log("laulau age: ", laulau.getAge(new Date()));// 33
console.log("laulau age in 5 years: ", laulau.getNext5yearAge());// 38
Call super class constructor using super(…);
constructor(id, name, dob, type) {
super(name, dob, type);
this.id = id;
}
Call super class method using super.methodName();
getNext5yearAge(){
let dob = super.getDob();
let today = new Date();
return (today.getFullYear() - dob.getFullYear()) + 5;;
}
A function is a block of code designed to perform a certain task. A function is run when it’s invoked or called by an action. functions are very important because they are written once and can be executed multiple times. They save you a lot of development time in that you don’t have to repeat writing the code in the function in multiple places where you need it.
Syntax
function add(num1, num2){
let sum = num1 + num2;
return sum;
}
Parameters
Function definitions do not specify data types for parameters. Functions do not perform type checking on the passed arguments. Functions do not check the number of arguments received. Parameters that are not objects are passed by value. Parameters that are objects are passed by reference which means, changes to them will reflect every where.
let user = {
"name":"Folau"
}
function changeToRandomName(user){
user.name = "Lisa";
console.log("user:",user);
}
console.log("user:",user);//{name: "Folau"}
changeToRandomName(user);//{name: "Lisa"}
console.log("user:",user);//{name: "Lisa"}
Default Values
If a parameter is not provided, then its value becomes undefined. You can set a default value to be used in case a parament is not passed.
/*
* Function Default values
*/
function hello(name, greeting = "Hello there! "){
return greeting+name;
}
/*
* Note that functions can take 0 or more parameters.
*/
let greetingFolau = hello("Folau");
console.log(greetingFolau);
// pass undefined instead null when intended to use default values.
let greetingLisa = hello("Lisa", undefined);
console.log(greetingLisa);
let greetingKinga = hello("Kinga", "Hi ");
console.log(greetingKinga);
Output
Hello there! Folau Hello there! Lisa Hi Kinga
Of course you can also check if parameters are undefined and set them to desired values
function sayHi(name, greeting){
// if(greeting==undefined){
// greeting = "Hello there! ";
// }
// undefined check with ??
greeting = greeting ?? "Hi there! ";
return greeting+name;
}
Function as a parameter
The function as a parameter will be executed every time the main function is called.
function sayHi(name, greeting){
// if(greeting==undefined){
// greeting = "Hello there! ";
// }
// undefined check with ??
greeting = greeting ?? "Hi there! ";
return greeting+name;
}
let greetingLau = sayHi("Folau");
console.log(greetingLau);
let greetingFusi = sayHi("Fusi", hello("Fusi "));
console.log(greetingFusi); //Hello there! Fusi Fusi
The arguments object
The arguments object contains an array of the arguments passed into the function. The arguments object behaves like an array though it is not an instance of the Array type.
let maxNum = findMax(1, 123, 500, 115, 44, 88);
console.log("maxNum: ",maxNum);//500
function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Anonymous functions
An Anonymous function is a function without a name. An Anonymous function cannot be called before its declaration.
//saveData();//Uncaught ReferenceError: Cannot access 'saveData' before initialization
let saveData = function(){
console.log("saving data to database");
}
saveData();
/*
* Functions that run immediately
*/
let name = "Lisa";
let age = 30;
(function() {
console.log("name: "+name+",age: "+age);
})(name);// parameters are passed from outside variables.
let multiply = (function(a,b){
return a * b;
})(10, 2);
// multiply here holds the result of the multiplication not an instance of the function
console.log(multiply);//20
Functions that run immediately(without being invoked)
let name = "Lisa";
let age = 30;
(function() {
console.log("name: "+name+",age: "+age);
})(name, age);// parameters are passed from outside variables.
Arrow functions
An arrow function is a shorter way of declaring an anonymous function.
let updateData = (name) => {
console.log("updating name in database.");
}
updateData();//updating name in database.