Javascript - Class (ES6)

About

This article is about Class in Javascript.

Class was introduced in ECMAScript 2015. Before the module pattern was used to create a class-like behavior.

Classes provide a simpler way to create objects and deal with inheritance than JavaScript's existing prototype-based inheritance.

The class syntax is not introducing a new object-oriented inheritance model to JavaScript but is a syntax sugar above prototype

Classes are functions.

Syntax

The class syntax has two ways to define a class:

  • class declarations.
  • a class expressions

Because a class is just a syntax sugar above function syntax, you can see that this syntax's map with:

  • function declarations
  • function expressions

The order of your code is important. You first need to declare your class and then access it.
This is not the case with function declaration.

Syntax:

  • The body of a class is the part that is in curly brackets {}.
  • There can only be one special method with the name “constructor”
  • The static keyword defines a static method for a class.
  • The extends keyword is used in class declarations or class expressions to create a class as a child of another class. As a class is just a function, a function prototyped may also be extended.

Declaration

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

Expression

  • unnamed
var Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
  • named. The name given to a named class expression is local to the class's body.
var Rectangle = class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

Example

Static function

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;

    return Math.sqrt(dx*dx + dy*dy);
  }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);

console.log(Point.distance(p1, p2));

where:

Class vs Function Syntax (and this)

class Animal { 

  speak() {
    return this;
  }
  
  static eat() {
    return this;
  }
  
}

let obj = new Animal();
let speak = obj.speak;
speak(); // undefined

let eat = Animal.eat;
eat(); // undefined

Autoboxing will not happen for a class syntax.

function Animal() { }

Animal.prototype.speak = function() {
  return this;
}

Animal.eat = function() {
  return this;
}



let obj = new Animal();
let speak = obj.speak;
speak(); // global object

let eat = Animal.eat;
eat(); // global object

Autoboxing will happen for a prototype syntax.
Based on the this value for which the function was called.

Extend

class Animal { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Dog extends Animal {
  speak() {
    console.log(this.name + ' barks.');
  }
}

var d = new Dog('Mitzie');
d.speak();

How to pass a class as function argument (typescript)?

Example:

function(clazzArgument: new (argConstructor: string) => Class) {
   const object:Class = new clazzArgument("1"); 
}

Management

Get the name / type

Javascript does not have the notion of class name but prototype. There is multiples way to determine the class that are shown below.

  • The context of the demo: A Foo object/function and a foo instance
function Foo() {}
var foo = new Foo();
  • Type of
console.log("The type of the function/class is: "+(typeof Foo)); // == "function"
console.log("The type of the instance is: "+(typeof foo)); // == "object"
  • is Instance of / isProprotypeOf
console.log("foo instance of Foo ?: "+(foo instanceof Foo));     // == true
console.log("Foo prototype of foo ?: "+(Foo.prototype.isPrototypeOf(foo)));   // == true
console.log("The constructor name is: "+foo.constructor.name);   // == "Foo" 
console.log("The name of the function is: "+Foo.name);  // == "Foo"    

setPrototypeOf

As a class is also a function, you can set a prototype to a class.

var Animal = {
  speak() {
    console.log(this.name + ' makes a noise.');
  }
};

class Dog {
  constructor(name) {
    this.name = name;
  }
}

// If you do not do this you will get a TypeError when you invoke speak
Object.setPrototypeOf(Dog.prototype, Animal);

var d = new Dog('Mitzie');
d.speak(); //Mitzie makes a noise.

instanceof

Javascript - instanceof

class Cat { 
  constructor(name) {
    this.name = name;
   }
}

var myCat = new Cat("Poesie");
console.log(myCat instanceof Cat); // true

this

In JavaScript, class methods are not bound by default. If you forget to bind a method and pass it, this will be undefined when the function is actually called.

It is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, you should bind that method.

Get the objects of a class

Documentation / Reference





Discover More
ES - ES6 Harmony (ES2015)

ECMAScript 6 (also known as ES2015). The first ECMAScript Harmony specification, it is also known as ES6 Harmony class declarations (class Foo...
Color Autocompletion List
How to create an Autocompletion functionality with CSS, Javascript and HTML

This article shows you how to create a search box with an autocompletion feature
JavaScript - new

The new word indicate a constructor of: an object via: a or a class. See a function. See
Javascript (Js|ECMAScript)

Javascript was born to run in the browser but may know with the advent of node run on the server side. See JavaScript is also known as: Mocha, LiveScript, JScript (Windows Implementation),...
Javascript - (Prototype Model|Prototypical object)

A prototype-based language has the notion of a prototypical object. Any object can: specify its own properties, either when you create it or at run time. be associated as the prototype for another...
Javascript - Module Pattern

This article shows classic design pattern with ECMAScript on how to organize javascript code with a structure that make possible to: get input return output and hide the implementation from the...
Chrome Dev Tool Source Debugger Scope
Javascript - This

this is a variable that has a reference value to the scope (namespace) this printThisobjthisobj Generally, this is the local scope but it may be changed. You can set this : in the call of a function...
Chrome Dev Tool Source Debugger Scope
Javascript - bind method

The bind method bind the object to the called function. Creates a new function which, when called, has its this set to the provided value, with a given sequence of arguments preceding any provided when...
Javascript - instanceof

instanceof instanceofObjectprototype An object created from a class will always be as an instanceof its class. The constructor of a function createdWITHOUT a prototype will beNOT recognized...



Share this page:
Follow us:
Task Runner