“This is the 12th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

👇 Read this article to learn more about 👇

  • Class constructor
  • Class instance, static, private property
  • Class instance, static, private method
  • Class inheritance
  • Getter and Setter
  • aboutclassSome extended knowledge

Before ES6 (ECMAScript6), JavaScript syntax did not support classes, so object-oriented programming methods could not be used directly. However, we could use function to simulate classes. With the update of JavaScript, the class keyword appeared in ES6. Can be used to define classes. Let’s see how it works.

class

Let’s look at how to declare a class using the class keyword.

class Animal {}// or

const Animal = class {}Copy the code

Before ES6, we modeled classes in this way.

function Animal(){}Copy the code

Class constructor

Each class can have its own constructor, which is a fixed constructor. When we call a class from new, the class calls its own constructor method.

  • It is used to pass parameters to a class when creating an object
  • Each class can have only one constructor, otherwise an error is reported

When a class is called from new, the constructor is called, which does the following:

  1. Create a new space in memory for creating new objects
  2. Inside this objectprototypeProperty will be assigned to that classprototypeattribute
  3. This inside the constructor refers to the new object being created
  4. Executes the internal code of the constructor
  5. Returns if the function does not return an objectthis
class Animal  {
  // Class constructor
  // For the receiver function
  constructor(name) {
    this.name = name; }}var a = new Animal("ABC");
console.log(a); // Animal { name: 'ABC' }
Copy the code

In the example above, we defined constructor in class, which is the constructor, and this stands for instance object.

This class, you can think of it as another way of writing the constructor, because it’s equivalent to its constructor, which is that the class itself points to the constructor.

console.log(Animal === Animal.prototype.constructor); // true
Copy the code

In fact, all methods on a class are placed on the Prototype property.

Attributes in a class

Instance attributes

Instance attributes must be defined in the class’s methods. As in the example above, we define the name attribute in the constructor.

class Animal{
  constructor(name,height,weight) {
    this.name = name;
    this.height = height
    this.weight = weight
  }
}
Copy the code

Static attributes

When an attribute is assigned to the class itself, rather than to its prototype, it is called static.

Static properties are accessed directly through the class, not in the instance.

class Foo{
  static name ='_island'
}

console.log(Foo.name);
Copy the code

Private property

Private attributes can only be read and written to a class, and cannot be referenced externally.

class Animal{
  #age;
  constructor(name,age){
    this.name=name
    this.#age=age
  }
}

var a = new Animal('_island'.18)
console.log(a); // Animal { name: '_island' }
console.log(a.name); // _island
console.log(a.age); // undefined
console.log(a.#age); // Private field '#age' must be declared in an enclosing class
Copy the code

We obtained through getOwnPropertyDescriptors to its properties, also can’t get.

console.log(Object.getOwnPropertyDescriptors(a))

{
  name: {
    value: '_island'.writable: true.enumerable: true.configurable: true}}Copy the code

Private fields can only be predefined in field declarations.

Public and private field declarations are an experimental feature (Phase 3) proposed by the JavaScript Standards Committee TC39. Support in browsers is limited, but it can be built with systems such as Babel.

Methods in a class

Instance methods

Prior to ES6, we defined methods in a class to be defined on the prototype of the class, preventing methods in the class from repeating on multiple objects.

function Animal() {}
Animal.prototype.eating = function () {
  console.log(this.name + " eating");
};
Copy the code

In ES6, it’s much simpler to define methods in a class. You can define them directly in a class, which is both elegant and readable.

class Animal{
  eating() {
    console.log(this.name + " eating"); }}Copy the code

A static method

Static methods are the same as static properties mentioned above. We use the static keyword in front of the method, and then call the method from the class name instead of the instance of the class.

class Animal{
  static createName(name) {
    return name
  }
}

var a2 = Animal.createName("_island");
console.log(a2); // _island
Copy the code

Private methods

Private methods are a common requirement in object orientation, but are not provided in ES6, and there is a method to implement it.

class Foo { __getBloodType() { return "O"; }}Copy the code

Note that by starting with an underscore we usually limit it to a private method, but it can still be called from outside the class

Class inheritance

The extends keyword is used to extend subclasses by creating a class as a subclass of another class.

It inherits attributes and methods from the parent class to the child class, reducing duplicate business code in the child class.

This is much more readable than the previous approach of modifying the stereotype chain to implement inheritance in ES5, and it is written succinctly.

Extends the use of

class Animal{}// Dog descends from Animal
class dog extends Animal {}Copy the code

Inherits the properties and methods of a class

In this example, we define a dog class that extends properties and methods from the Animal class through the extends keyword.

In the constructor method of a subclass, we use the super keyword, which must be present in a subclass otherwise new instances will throw an exception. This is because a subclass’s This object inherits from its parent class, and if you don’t call super, the subclass doesn’t get this.

class Animal {
  constructor(name) {
    this.name = name;
  }
  eating() {
    console.log(this.name + " eating"); }}// Dog descends from Animal
class dog extends Animal {
  constructor(name, legs) {
    super(name);
    this.legs = legs;
  }
  speaking() {
    console.log(this.name + " speaking"); }}var d = new dog("tom".4);
d.eating(); // tom eating
d.speaking(); // tom speaking
console.log(d.name); // tom
Copy the code

Super

The super keyword is used to access and call functions on the parent object of an object.

Super means super, top level, superclass

Before you can use this in a subclass constructor or return a default object, you must first call the superclass constructor through super.

In the following code, the constructor method of the subclass first calls the super method, which represents the constructor of the superclass, meaning that it actually calls the constructor of the superclass after we pass in the argument.

class Animal{
  constructor(name)}class dog{
  constructor(name,type,weight){
    super(name)
    this.type=type
    this.weight=weight
  }
}
Copy the code

The following code calls the method of the parent class using super

class Animal {
  constructor(name) {
    this.name = name;
  }
  eating() {
    console.log(this.name + " eating"); }}// Dog descends from Animal
class dog extends Animal {
  constructor(name, legs) {
    super(name);
    this.legs = legs;
  }
  speaking() {
    super.eating()
    console.log(this.name + " speaking"); }}var d = new dog("tom".4);
d.speaking(); // tom eating tom speaking
Copy the code

Getter and Setter

The get and set keywords can also be used inside a class to intercept the access behavior of a property by corresponding to a property setting store and value function.

class Animal {
  constructor() {
    this._age = 3;
  }

  get age() {
    return this._age;
  }

  set age(val) {
    this._age = val; }}var a = new Animal();
console.log(a.age); / / 3
a.age = 4;
console.log(a.age); / / 4
Copy the code

About Class Extension

Strict mode

Inside classes and modules, the default is strict mode, so there is no need to use Strict to specify the runtime mode. As long as your code is written in a class or module, only strict mode is available.

The name attribute

Classes in ES6 are just a wrapper around ES5 constructors, so many of the functions’ properties are inherited by class, including the name attribute.

class Animal{}console.log(Animal.name); // Animal
Copy the code

Variable ascension

There is no variable promotion for class, unlike in ES5 where we implement classes, the function keyword has variable promotion.

new Foo(); // ReferenceError
class Foo {}
Copy the code

conclusion

After ES6, the syntax for defining a class and its internal property methods, as well as inheritance operations, has become very concise and easy to understand. Class is a syntactic sugar, which is implemented internally by ES5 syntax. Some browsers do not support class syntax, so we can use Babel to convert.

JS advanced series of articles

  • Pure functions of functional programming
  • Curritization of functional programming
  • Combinatorial functions of functional programming