Quickview: A quick es6 Classes Overview

I keep meaning to put together quickviews of languages I use, almost like cheatsheets, but like a pocket guide overview of language syntax and uses. I recently brushed up on es6 classes.

So here’s my first attempt at a quickview: es6 classes

Basics

Constructors

1
2
3
4
5
class NameOfClass {
    constructor(args) {
        ...
    }
}

Setting class level variables:

Adding parameters to this

1
2
3
4
5
class NameOfClass {
    constructor(name) {
        this.name = name;
    }
}

Methods

Add a method to an es6 class

1
2
3
4
5
6
7
8
9
class NameOfClass {
    constructor(name) {
        this.name = name;
    }

    methodName() {
        return "Hi " + this.name + "!"
    }
}

Default values for arguments

Set a default value for an argument in an es6 class

1
2
3
4
5
...
    constructor(name = "Default") {
        this.name = name;
    }
...

Interpolation

Template strings and interpolating variables (injecting a variable):

You use ${…} and backtick syntax `..`

1
2
3
4
5
6
7
8
9
class NameOfClass {
    constructor(name) {
        this.name = name;
    }

    methodName() {
        return `Hi ${ this.name } !`
    }
}

Note: You can put any kind of valid javascript in the interpolation, including methods.

Advanced

Extending

Extend one class with another class in es6 classes.

1
2
3
class OtherClass extends NameOfClass {
...
}

Call parent class

Referencing the parent class constructor with super(…);

1
2
3
4
5
6
class OtherClass extends NameOfClass {
    constructor(originalClassArg, newClassArg) {
        super(originalClassArg); // You are calling the original class' constructor
        this.newClassArg = newClassArg;
    }
}

Overriding

Extending a parent class method without overriding it:

1
2
3
4
5
6
7
8
9
10
11
12
class OtherClass extends NameOfClass {
    constructor(originalClassArg, newClassArg) {
        super(originalClassArg);
        this.newClassArg = newClassArg;
    }
    methodName() {
        let methodValue = super.methodName();
        ...
        // more logic, do something with methodValue perhaps
        ..
    }
}

References:

Recommended Course:

https://completereactcourse.com

Read more on template strings:

https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/
https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

Javascript built in array methods ES5 and ES6

Inspired by a Sitepoint article:

https://www.sitepoint.com/filtering-and-chaining-in-functional-javascript/

They highlighted built in javascript array methods. I decided to explore two ES5 and ES6 built in array methods; filter and map.

Javascript Array Filter ES5 and ES6

The filter method lets you easily filter an array using a callback style approach. Your callback handles the condition, the filter loops through your array and lets you apply the condition to each value in the array.

1
array.filter(function)

// ES5

1
2
3
4
5
6
7
var list = ['oranges','apples','pears'];
var filteredList = list.filter(
function(value) {
// condition
return value.length <= 5;
}
)

// Result: filteredList = [“pears”]

// ES6

1
2
3
4
let list = ['oranges','apples','pears'];
let filteredList = list.filter(
value => value.length <= 5
)

// Result: filteredList = [“pears”]

Javascript Array Map ES5 and ES6

Use map to loop through elements of an array, on each loop you can create a new element that is appended to a new array. The result of map is a new array, based on the return value in the function in the map declaration.

1
array.map(function)

// ES 5

1
2
3
4
var list = ['oranges','apples','pears'];
var filteredList = list.map(function(value) {
return value.length;
})

// result: filteredList = [7, 6, 5]

// ES 6

1
2
3
4
let list = ['oranges','apples','pears'];
let filteredList = list.map(
value => value.length
)

// result: filteredList = [7, 6, 5]

Chaining javascript array methods; filter and map

As mentioned in the article, a great feature to these array methods is the ability to chain them:

// ES 5

1
2
3
4
5
6
7
8
9
var list = ['oranges','apples','pears'];
var filteredList = list.filter(
function(value) {
// condition
return value.length <= 5;
}
).map(function(value) {
return value.length;
})

// result: filteredList = [5]

// ES 6

1
2
3
4
5
6
let list = ['oranges','apples','pears'];
let filteredList = list.filter(
value => value.length <= 5
).map(
value => value.length
)

// result: filteredList = [5]

Conclusion

There are many more powerful lightweight built in javascript methods that are worth exploring. Taking the time to learn them can help save time and effort.

Javascript inheritance

Thoughts and notes on inheritance in javascript.

You can use the built in .call() method to extend a javascript class.

Syntax:

1
2
3
4
var InheritClass = function() {}
var YourClass = function() {
InheritClass.call(this);
}

An example with “Animal”. Inherit an Animal class inside a Cow class.

Remember to create a new instance of Cow. Only in the object instance can you call the methods and properties.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var Animal = function() {
this.speak = "no speak set";
this.food = "no food set";
this.action;
this.says = function() {
console.log(this.speak);
};
this.eats = function() {
console.log(this.food);
};
};
var Cow = function () {
Animal.call(this);
};
// Cow.says(); // This wont work
//You have to create a new object as indicated below
var Bessie = new Cow();
//You will see the default values
Bessie.says();
Bessie.eats();
Bessie.speak = "Moo";
Bessie.food = "Hay";
//You see your newly set values
Bessie.says();
Bessie.eats();

So can you use the same concept to inherit from multiple classes? Yes.

You can inherit from multiple classes and keep adding to the current class.

Eg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var Animal = function() {
this.speak = "no speak set";
this.food = "no food set";
this.action;
this.says = function() {
console.log(this.speak);
};
this.eats = function() {
console.log(this.food);
};
this.actions = function() {
console.log(this.action);
};
};
var Farm = function() {
this.farm = "no farm";
this.whichFarm = function() {
console.log(this.farm);
};
};
var Cow = function () {
Animal.call(this);
Farm.call(this);
};
var Bessie = new Cow();
Bessie.says();
Bessie.eats();
Bessie.whichFarm();
Bessie.speak = "Moo";
Bessie.food = "Hay";
Bessie.farm = "Old Mc Donald's";
Bessie.says();
Bessie.eats();
Bessie.whichFarm();

Javacript: More functional, less object oriented

A colleague pointed out that when I program in javascript I’m trying to force object oriented programming onto javascript. Rather than keeping with the javascript style of programming. The main problem is I rely on the “new” keyword in my javascript code.

The scenario:

I want a base object, DataInterface, that can handle api methods and data.

I have reusable methods that are interfaced, and then I want to be able to extend “DataInterface” and have the endpoint updated for each instance of the class.

The ideas:

It can be further debated whether this is the right solution for the scenario, but below is the outcome of the discussion:

DataInterface class with methods:

Eg:

1
2
3
4
var DataInterface = function() {
    this.getAll : function() {}; //just an example
    this.getByField : function(field, value) {}; //just an example
}

And this base object has an api endpoint attribute

Eg:

1
2
3
var DataInterface = function() {
    this.endpoint = ‘/endpoint’;
}

Then I want to extend off of this object and have specific data sets,

Eg

1
2
Products.endpoint = ‘one’;
Leads.endpoint = ‘two’;

And then Products and Leads can have additional extended methods, but they inherit the same original behavior from the base class.

The focus:

I am going to focus on just updating the endpoint for two instances of DataInterface, and exclude any methods:

What I originally wrote:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var DataInterface = function() {
    var endpoint;
    this.setEndpoint = function(_endpoint) {
        endpoint = _endpoint;
    };
    this.getEndpoint = function() {
        return endpoint;
    };
    return this;
}

var ProposalService = new DataInterface();
var ProductService = new DataInterface();
ProposalService.setEndpoint('one');
ProductService.setEndpoint('two');

console.log(ProposalService.getEndpoint());
console.log(ProductService.getEndpoint());

What this will output is ‘one’, and then ‘two’ in the console. Two instances of the DataInterface has been created with two unique endpoints.

Out with the new

However, if you remove the “new” keyword, which would make it more “javascript-like”:

Using the same class, but removing “new”.

1
2
3
4
5
6
var ProposalService = DataInterface();
var ProductService = DataInterface();
ProposalService.setEndpoint('one');
ProductService.setEndpoint('two');
console.log(ProposalService.getEndpoint());
console.log(ProductService.getEndpoint());

What will happen now is the console will print out ‘two’, ‘two’. Instead of two instances, we have the same instance being pointed to by 2 variables. So the endpoint is not unique.

In comes the factory pattern

So if we rewrite the code a bit, and have DataInterface as a factory pattern that returns an object, then we can achieve the same result but without the new keyword.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var DataInterface = function() {
    return {
        endpoint : '',
        setEndpoint : function(_endpoint) {
            this.endpoint = _endpoint;
        },
        getEndpoint : function() {
            return this.endpoint;
        }
    };
};

var ProposalService = DataInterface();
var ProductService = DataInterface();
ProposalService.setEndpoint('one');
ProductService.setEndpoint('two');
console.log(ProposalService.getEndpoint());
console.log(ProductService.getEndpoint());

You will now get the output of ‘one’ and ‘two’ in the console, and we did not rely on the “new” keyword.

Just a handy little snippet of code to remember how to not use “new” in javascript when creating instances.