1/3/2019

Modules

Module patterns have been built into JavaScript libraries for some time, but they are now available native in the language.

Modules are single instances of code designed to be reused throughout an application.

Modules are heavily used in NodeJS and Angular Applications.

Module Exporting


        // /lib/math.js
        export function multiply(x,u){
            return x * u;
        }
        export const pi = 3.14
        

    import {multiply, pi} from 'lib/math';
    console.log(multiply(pi, 4));
    

Module Importing

import {multiply, pi} from 'lib/math';
  • import - All imports occur before any other code
  • {multiply, pi} - Imported objects must be properly exported.
  • from
  • 'lib/math' - Relative path to the file. .js file extension is not required.

JavaScript Classes

Classes provide JavaScript a better opportunity to behave like an Object Oriented Programming Language.

You could make it behave like OOP by enforcing strict patterns.

Caution

This is where this starts getting complicated.

Puns

Class Declaration

You must declare a class before you use it.


class Square{
}
    

Usage


var sq = new Square();
    

Class Structure

  • Constructor
  • Methods

Constructors

A constructor is a specific method used in the initialization of a class.

There can only be one constructor per class.


 class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }
 }
   

var rc = new Rectangle(10, 15);
  

What is an instance of a class?

The class is like a blueprint, an object is an actual instance of the class.

Methods

No code is allowed outside of method. The function keyword is not required.


 class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }

    calcArea(){
        return this.height * this.width;
    }
 }

        var rc = new Rectangle(10, 10);
        console.log(rc.calcArea());
        

Get Methods

Get methods allow you to create dynamic read only properties without requiring the user to call a method.


 class Rectangle{
    constructor(height, width){
        this.height = height;
        this.width = width;
    }

    get area(){
        return this.calcArea();
    }
    calcArea(){ 
        return this.height * this.width;
    }
 }
 

    var rc = new Rectangle(10, 10);
    console.log(rc.area);
        

MDN Documentation

Set Methods


 class Log{
    constructor(){
    this.log = [];
    }
    get logHistory(){
        return this.log; 
    }
    set currentLog(value){
        this.log.push(value);
    }
 }
 

    var lg = new Log();
    lg.currentLog = 'new message';
    console.log(lg.logHistory);
        

    class Person {

        constructor(){}

        get fullName() {
            return this.firstName + ' ' + this.lastName;
        }

        set fullName (name) {
            var words = name.toString().split(' ');
            this.firstName = words[0] || '';
            this.lastName = words[1] || '';
        }

    }

            

Static Methods

Static Methods are methods associated with a class, but are not a part of the instance of the class.

Static Method Example


class Number{
    constructor(n){
        this.num = n;
    }
    increment(){
        this.num++;
    }
    static square(num){
        return num * num;
    }
}
   

var x = new Number(1);
x.increment();
x.square() //error
Number.square(2); //return 4
        
    

Sub Classes

Subclasses extend an existing class. It shares the same methods and properties of it's parent class.

Sub Class Example


class Rectangle {
    constructor(height, width){
        this.name = 'Rectangle';
        this.height = height;
        this.width = width;
    }
  get area(){
    return this.height * this.width;
  }
}


class Square extends Rectangle{
    constructor(length){
        super(length, length);
        this.name = 'Square';
    }
}

var rect = new Rectangle(10, 5);
console.log(rect.name); //Rectangle
console.log(rect.area); //50

var sq = new Square(5);
console.log(sq.name); //Square
console.log(sq.height); //5
console.log(sq.area); //25
        

Questions?

TypeScript

TypeScript is a superset of JavaScript that compiles down to vanilla JavaScript that can be consumed by any browser or NodeJS application.

TypeScript

  • First appeared in Oct 2012
  • The lead architect of C# and creator of Delphi worked on the development of TS
  • It finds and outputs errors when it compiles. It lets you know you've messed up before you run your code in browser.

Compilation

main.scss

main.css

main.ts

main.js

TypeScript Syntax


function logger(message){
    console.log(`Log: ${message}`)
} 

logger('Hello World');
                

function logger(message:string){
    console.log(`Log: ${message}`)
} 

logger('Hello World');
logger(1); //Outputs an error in the compiler.
                

Getting TypeScript

Editor Plugins

Node.js

npm install -g typescript

tsc helloworld.ts

TypeScript - Types

You use types to declare what type of variable you are declaring. The TypeScript compiler will notify you if you missuse a type.

Boolean Type


let isValid: boolean = false;
    
function test(apply: boolean){
    if (apply === true){
    }
}

test(isValid);
test('true'); // Error.
        

Number


const pi: number = 3.14;

function area(radius: number) : number{
    return pi * (Math.pow(radius, 2));
}

let a: number = area(2); 
let b: string = area(2); //Error due to b being a string
        

String


const firstName: string = 'Jon';
const lastName: string = 'Middaugh';

function fullName(fName, lName) : string{
    return `${fName} ${lName}`;
}
        

Array

Two ways to declare. Both are correct.


    let list: number[] = [1, 2, 3];  //similar to Java
    let list: Array<number> = [1, 2, 3];  // similar to C#
        

Any

Best used when interacting with other libraries and frameworks.

Some quality scanners discourage this.


let e: any = 30;
e = true;
e = "Hello World";
        

Interfaces

An interface provides a blueprint for JavaScript objects and classes.

TypeScript Interface API

Great article on using Classes and Interfaces together with TypeScript

Interface Example



interface Person {
    firstName: string;
    lastName: string;
}        

function getName(person: Person){
}
        

Interface Example



interface Shape {
    Name: string;
    Sides: number;
    Height: number;
    Width: number;
}        

let rectangle: Shape =  {
   Name: 'Rectangle',
   Sides: 4,
   Height: 20,
   Width: 20 
}
        

Classes

TypeScript allows you to enforce rules upon a class as well.

Typescript Class Docs

Classes and Interfaces

Classes and Interfaces play well with each other.

Example


class Student  implements Person{
    fullName: string;
    firstName: string;
    lastName: string;
    constructor( firstName: string,  middleInitial: string,  lastName: string) {
        this.fullName = `${firstName} ${middleInitial}  ${lastName}`;
        this.firstName = firstName;
        this.lastName = lastName
    }
}

interface Person {
    firstName: string;
    lastName: string;
}
//Accepts either a person or student
function greeter(person : Person) {
    return "Hello, " + person.firstName + " " + pergson.lastName;
}
       

Class constructor changes


class Student  implements Person{
    fullName: string;
    constructor(public firstName: string, public middleInitial: string, public lastName:string) {
        this.fullName = `${firstName} ${middleInitial}  ${lastName}`;
    }
}
       

Adding public to the variable automatically generates the assignment.

Interface Example



class Rectangle implements Shape{
  constructor(public name: string, public sides: number, public height: number, public width: number){
  }
}
        

Casing matters on your types

Wrong


function logic(foo: String): String; 
                

Right


function logic(foo: string): string; 
                

Number, String, Boolean, and Object refer to reserved words in JavaScript.

Before you leave - http://codepen.io/

  • Convert these declarations into TypeScript Declarations
    • let foo = 'bar';
    • const pi = 3.14;
    • const today = new Date();
    • let items = [1, 2, 3, 5]
    • let items = ["Test", 2, today, 5]
  • Create an interface called Shape and has the following properties.
    • Name -> string
    • Sides -> number
    • Height -> number
    • Width -> number
  • Create a class called Rectangle and have it implement Shape
>