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.
// /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));
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. 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.
this
starts getting complicated.You must declare a class before you use it.
class Square{
}
var sq = new Square();
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);
The class is like a blueprint, an object is an actual instance
of the class.
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 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);
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 are methods associated with a class, but are not a part of the instance of the class.
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
Subclasses extend an existing class. It shares the same methods and properties of it's parent class.
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
TypeScript is a superset of JavaScript that compiles down to vanilla JavaScript that can be consumed by any browser or NodeJS application.
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.
npm install -g typescript
tsc helloworld.ts
You use types to declare what type of variable you are declaring. The TypeScript compiler will notify you if you missuse a type.
let isValid: boolean = false;
function test(apply: boolean){
if (apply === true){
}
}
test(isValid);
test('true'); // Error.
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
const firstName: string = 'Jon';
const lastName: string = 'Middaugh';
function fullName(fName, lName) : string{
return `${fName} ${lName}`;
}
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#
Best used when interacting with other libraries and frameworks.
Some quality scanners discourage this.
let e: any = 30;
e = true;
e = "Hello World";
An interface provides a blueprint for JavaScript objects and classes.
Great article on using Classes and Interfaces together with TypeScript
interface Person {
firstName: string;
lastName: string;
}
function getName(person: Person){
}
interface Shape {
Name: string;
Sides: number;
Height: number;
Width: number;
}
let rectangle: Shape = {
Name: 'Rectangle',
Sides: 4,
Height: 20,
Width: 20
}
TypeScript allows you to enforce rules upon a class as well.
Classes and Interfaces play well with each other.
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 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.
class Rectangle implements Shape{
constructor(public name: string, public sides: number, public height: number, public width: number){
}
}
function logic(foo: String): String;
function logic(foo: string): string;
Number
, String
, Boolean
, and Object
refer to reserved words in JavaScript.let foo = 'bar';
const pi = 3.14;
const today = new Date();
let items = [1, 2, 3, 5]
let items = ["Test", 2, today, 5]
Shape
and has the following properties.
Rectangle
and have it implement
Shape