A definition

Class is a new feature in ES6 that allows you to define a class. In fact, class is just a syntactic sugar, which is another way of writing the constructor. What is grammar sugar? Is a syntactically elegant solution to avoid coding errors and make coding more efficient, in short, a portable way to write.

The new class writing method simply makes the writing of object prototypes clearer and more like the syntax of object-oriented programming.

2 use

The usage is the same as with the constructor, using new to generate the object instance

  • A constructor is a function called with the new keyword, which is essentially a function
  • An instance is an object. Because the instance is the return value after the constructor new is called. A constructor always returns an object. The return value you want to change to another non-object cannot be changed.

class Person {}let andy = new Person();
typeof Person // "function"
typeof andy // "object"

Copy the code

Each class must have constructor

The constructor method is the default method of the class and is automatically called when an object instance is generated using the new command. Each class must have a constructor; if no declaration is displayed, the JS engine automatically adds an empty constructor to it

The constructor method. This keyword represents the instance object. The data type of a class is a function, and the class itself points to a constructor.

class Person {}/ / is equivalent to
class Person {
  constructor () {
    this.name = name; }}Copy the code

Static properties/methods, instance properties/methods

1) Prototype attributes and methods

Properties and methods defined within constructor, defined on this, belong to instance properties and methods, and otherwise to stereotype properties and methods.

2) Static properties [not inherited by instance]

Static properties refer to properties of the Class itself, class.propName, not properties defined on the instance object (this). This is done by adding the static keyword before the instance attribute.

3) Static methods [not inherited by instance]

class A {
    static classMethod() {
        return 'hello';
    }
}
A.classMethod();
console.log(A.classMethod());
// 'hello'

const a = new A();
a.classMethod();
// TypeError: a.classMethod is not a function
Copy the code

A class is the prototype of an instance, and all methods defined in a class are inherited by the instance. The static keyword before a method means that the method is not inherited by the instance but is called directly from the class. This is called a “static method”.

class Person {
  static test = 1; // Static attributes
  constructor (name) {
    this.name = name
  }

  say () {
    console.log('hello')}}let andy = new Person()

andy.hasOwnProperty('name') // true
andy.hasOwnProperty('say') // false

Copy the code

1) Es5

function Person () {
  this.name = name;
};
Person.prototype.say = function () {
    console.log('hello')}let andy = new Person()

andy.hasOwnProperty('name') // true
andy.hasOwnProperty('say') // false

Copy the code

Five inheritance

Class can be inherited through the extends keyword

1) Static methods of the parent class are also inherited by subclasses.

class A {
  static hello() {
    console.log('hello world'); }}class B extends A {
}

B.hello()  // hello world

Copy the code

2)

class Cat extends Animal {
    constructor(name, age, color) {
        // Call parent constructor(name, age)
        super(name, age);
        this.color = color;
    }
    toString() {
        return this.color + ' ' + super.toString(); // Call the parent toString()}}Copy the code

The super keyword appears in both the constructor and toString methods, where it represents the parent’s constructor, which is used to create a new parent’s this object.

Subclasses must call the super method from the constructor method, or new instances will report an error. This is because the subclass’s this object must be molded by the parent’s constructor to get the same instance attributes and methods as the parent, and then processed to add the subclass’s instance attributes and methods. If you don’t call super, your subclasses don’t get this.

class Animal { / *... * / }

class Cat extends Animal {
  constructor(){}}let cp = new Cat();
// ReferenceError

Copy the code

Cat inherits from Animal, but its constructor does not call super, causing an error when creating a new instance.

If the subclass does not define a constructor method, this method is added by default, as shown below. That is, any subclass has a constructor method whether or not it is explicitly defined.


class Cat extends Animal {}/ / is equivalent to

class Cat extends Animal {
    constructor(. args) {
        super(...args);
    }
}

Copy the code

Another point to note is that es5 constructors can access this before calling the parent constructor, but ES6 constructors can’t access this before calling the parent constructor (that is, super).

class A {
  constructor(x, y) {
    this.x = x;
    this.y = y; }}class B extends A {
  constructor(x, y, name) {
    this.name = name; // ReferenceError
    super(x, y);
    this.name = name; / / right}}Copy the code

In the code above, the subclass’s constructor method uses the this keyword without calling super, which results in an error and is correct after the super method.

Getters and Setters

Each class must have a constructor. If no declaration is displayed, the JS engine automatically adds an empty constructor to it:

class Person {
  get name () {
    return '1'
  }
  set name(val) {
    console.log('set: ' + val)
  }
}

let andy = new Person()
andy.name = 'andy' // setter andy
andy.name / / 1


Copy the code

Class expression

Define an internal class name for the class if necessary, or omit it if not required:

// We need to use the class name const Person = class Obj {getClassName () {return obj.name}} // we don't need to copy code const Person = class {}Copy the code

Class that executes immediately:

let andy = new class {
  constructor(name) {
    this.name = name
  }
  sayName() {
    console.log(this.name)
  }
}('andy')

andy.sayName() //andy
Copy the code

Review the implementation of new as a sidebar

The new operator creates an instance of a user-defined object type or of a built-in object with a constructor.

function _new(constructor, ... args) {
    // The constructor type is valid
    if(typeof constructor! = = 'function') {
      throw new Error('constructor must be a function');
    }
    // Create an empty object instance
    let obj = new Object(a);// Bind the constructor prototype to the newly created object instance
    obj.__proto__ = Object.create(constructor.prototype);
    // Call the constructor and determine the return value
    let res = constructor.apply(obj, args);
    let isObject = typeof res === 'object'&& res ! = =null;
    let isFunction = typeof res === 'function';
    If there is a return value and the return value is an object type, it is returned, otherwise the newly created object is returned
    return isObject || isFunction ? res : obj;
};

function Person (name) {
  this.name = name;
};
Person.prototype.say = function () {
    console.log('hello')};let p1 = _new(Person, '111'); // {name: "111"}
console.log(p1); // {name: "111"}

Copy the code

reference

    • Basic syntax for ECMAScript 6 Class by Yifeng Ruan

conclusion

  • Class is a syntactic sugar, the underlying layer of which is created through the constructor.

  • All methods of a class are defined on the prototype property of the class.

  • Static methods: Add static before a method to indicate that the method is not inherited by the instance, but is called directly from the class.

  • Static property: Add static before the property to refer to the property of the Class itself, not the property defined on the instance object (this).

  • The constructors of ES5 can access this before calling the parent constructor, but the constructors of ES6 cannot access this before calling the parent constructor (that is, super).

  • super

    • Called as a function, representing the constructor of the parent class
    • Called as an object, in a normal method, pointing to a prototype object of the parent class; In static methods, point to the parent class.
  • Class does not have variable promotion

new A(); // ReferenceError 
class A {};

Copy the code