JavaScript Classes: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 43: Line 43:


===Constructor===
===Constructor===
{{External|https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor}}
The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the <code>super</code> keyword to call the constructor of the super class.
===Prototype Methods===
===Prototype Methods===
===Static Methods===
===Static Methods===

Revision as of 23:19, 21 January 2020

External

Internal

Overview

A JavaScript class is a syntactical superstructure in top of the language's existing prototype-based inheritance, and it does not introduce a new object-oriented inheritance model in JavaScript. A class is a special function, so like in the functions' case, a class syntax has two components: declarations and expressions.

Class Hoisting

An important difference between function declaration and class declaration is that function declaration and hoisted, while the class declarations are not: you first need to declare the class and then access it, otherwise a ReferenceError is thrown.

Declaration

Use the class keyword:

class Simplest {
  constructor(content) {
    this.content = content;
  }
}

Class Expression

A class expression is another way to define a class, and it can be named or unnamed. The name given to a named expression is local to the class' body. It can be retrieved through the class' and not an instance's name property.

let Simplest = class {
  constructor(content) {
    this.content = content;
  }
}
console.log(Rectangle.name);

Syntax Elements

Body

The body of a class is contained within curly braces {...}. It contains class members: constructor and methods. The body of a class is executed in strict mode, the code is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript.

Constructor

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. A constructor can use the super keyword to call the constructor of the super class.

Prototype Methods

Static Methods