The class syntax is just a syntactic helper to reduce the amount of boilerplate in JavaScript when using class like patterns. Unlike some other ES6 features, it does not introduce new functionality. Firstly, here is how to simulate an object that is generated from another without the keyword:
function Api(location) { this.location = location; // When the function is explicity named, easier to follow stack traces are given. this.run = function run(callback) { const data = { '/location1': ['location1', 'data'], '/location2': ['/ocation2', 'data'] }; setTimeout(() => { this.onDataRecieved(data[this.location], callback) }, 500); }; this.onDataRecieved = function onDataRecieved(data, callback) { callback(data); }; } const location1Api = new Api('/location1'); location1Api.run(function(data) { console.log('Retrieved: ', data); // Retrieved: [ 'location1', 'data' ] });
This works, but takes quite a bit of manual work in the Api class definition. For example every function is defined with a long assignment that uses the name twice because named functions give better stack traces. There is also nothing direct in the syntax that indicates this is a class instead of a normal function; You have to actually read through the code.
Classes do the same thing as the above, but reduce a lot of syntax:
class Api { constructor(location) { this.location = location; } run(callback) { const data = { '/location1': ['location1', 'data'], '/location2': ['/ocation2', 'data'] }; setTimeout(() => { this.onDataRecieved(data[this.location], callback) }, 500); } onDataRecieved(data, callback) { callback(data); }; }
Unlike a Function Declaration, classes are not hoisted to the top of the file before running. Other than that, the class keyword is literally just a syntax shortener for the previous way of defining classes in JavaScript. For example, since class is actually just a type of instantiable object like functions are, properties can be attached to it. This is the equivalent of static properties in other languages:
Api.myClassProperty = 'test';
ES6 Classes now have standard support across all modern browsers (except IE 11), so transpilers usually do not need to be used for them in most situations.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/es6Class.js