JavaScript Class in ES6 , write less, do more - AkuCode
Traditionally JavaScript is the only mainstream language with prototype-based inheritance. Programmers switching to JS from class-based language found it puzzling, but ES2015 introduced classes, which are just syntactic sugar over the inner working, but changed a lot how we built JavaScript programs.
Now inheritance is very easy and resembles other object-oriented programming language:
Now inheritance is very easy and resembles other object-oriented programming language:
class Person {
contructor(name){
this.name = name
}
hello(){
return ‘hello, Iam’ + this.name+ ‘.’
}
}
class Actor extend Person{
hello(){
return super.hello()+ ‘I am an actor.’
}
}
var tomCruise = new Actor(‘Tom Cruise’)
tomCruise.hello()
(the above program prints “Hello, I am Tom Cruise. I am an actor.”)
Classes do not have explicit class variable declarations, but you must initialize any variable in the constructor.
Constructor
Classes have a special method called constructor which is called when a class is initialized via new.
Super
The parent class can be referenced using super().
Getters and Setters
A getter for a property can be declared as
class Person{
get fullName(){
return `${this.firtsName} ${this.lastName}`
}
}
Setters are written in the same way:
class Person{
set age(years){
this.theAge = years
}
}
Modules
Before ES2015, there were at least 3 major modules competing standards, which fragmented the community:
- AMD
- RequireJS
- CommonJS
ES2015 standardized these into a common format.
Importing Modules
Importing is done via the import … from … construct:
import + from ‘mymodule;
import React from ‘react’
import { react, Componenent} from ‘react’
import React as MyLibrary from ‘react’
Exporting modules
You can write modules and export anything to other modules using the export keyword:
export var foo = 2
export function bar(){ /*…*/}
Template Literals
Template literals are a new syntax to create string:
const aString = `A string`
They provide a way to embed expressions into string, effectively interpolating the values, by using the ${a_variable} syntax:
const var = ‘test’
const string = `something ${var}` //something test
You can perform more complex expressions as well:
const string = `something ${1 + 2 + 3}`
const string2 = `something ${foo() ? ‘x’ : ‘y’}`
And strings can span over multiple lines:
const string3 = `Hey
this
string
is awesome!`
Compare how we used to do multiline string pre-ES2015:
var str = ‘One\n’ +
‘Two\n’ +
‘Three’
Default Parameters
Functions now support default parameters:
const foo = function(index = 0, testing = true){/* … */}
foo()
The spread operator
You can expand an array, an object or a string using the spread operator.
Let’s start with an array example. Given
const a = [1,2,3]
You can create a new array using
const b = […a,4,5,6]
You can also create a copy of an array using
const c = […a]
This work for object as well. Clone an object with:
const newObj = {…oldObj}
Using strings, the spread operator creates an array with each char in the string:
const hey = ‘hey’
const arrayized = […hey] // [ ‘h’, ’e’, ’y’]
This operator has some pretty useful applications. The most important one is the ability to use an array as function argument in a very simple way:
const f = (foo, bar) => {}
const a = [1, 2]
f(…a)
(in the past you could do this using f.apply(null, a) but that's not a niche and readable).
Desctructuring assignments
Given an object, you can extract just some values and put them into name variables:
const Person = {
firstName: ‘Tom’,
lastName: ‘Cruise’,
actor: true,
age: 54,
const (firstName: name,age) = person
}
Name and age contain the desired values.
The syntax also works on arrays:
const a = [1,2,3,4,5]
[first, second, , ,fifth] = a
Enhanced Object Literals
In ES2015 Object Literals gained superpowers.
Simpler syntax to include variabels
Instead of doing
const something = ’y’
const x = {
something : something
}
You can do
const something = ‘y’
const x = {
something
}
Prototype
A prototype can be specified with
const anObject = { y: ‘y’}
const x = {
__proto__: anObject
}
Super()
const anObject = { y: ‘y’, test: () => ‘zoo’ }
const x = {
__proto__: anObject,
test(){
return super.test()+ ‘x’
}
}
x.test() //zoox
Dynamic properties
const x = {
[‘a’ + ‘_’ + ‘b’]: ‘z’
}
x.a_b //z
For-of loop
ES5 back in 2009 introduced forEach() loops. While niche, they offered no way to break, like for loops always did. ES5 introduced the for-of loop, which combines the consiness of forEach with the ability to break:
for (const v of [‘a’, ‘b’, ‘c’]){
console.log(v);
}
for (const [I, v] of [‘a’, ‘b’, ‘c’].entries()){
console.log(I, v)
}
Map and Set
Map and Set (and their respective garbage collected Weakmap and WeakSet) are the official implementations of two very popular data structures.
Comments