Class knowledge review

  1. Console output class

    Red represents that the output is an instance object, and blue represents who created the instance object.

    • Person {}

    If the constructor of the class does not receive parameters, the created instance objects will look the same.


  2. Constructor constructor

    1
    2
    3
    4
    5
    class Person {
    constructor (name, age) {
    this.name=name
    this.age=age
    }}

    Who is this in the constructor? this points to the instance object of the class.

    The constructor can not be written. But if you don’t write it, the instance objects are the same.


  3. General methods: custom methods other than constructors.

    Do not write functions. Directly methodname() in the class.

    Common methods are placed on the prototype object of the class. The methods placed on the prototype object are for the instance.


    In general methods this refers to the instance object. That is, when a generic method is invoked through an instance, this in the generic method refers to the instance. But here you can use the call/apply/bind method to change the this pointer.


  4. Inherit extends

    1
    class Student extends Person {}

    The Student class does not have to write a constructor, because the parent class Person has a constructor. When a subclass does not write a constructor, it directly inherits the constructor of the parent class.


    When a subclass needs to customize a new constructor, because the parameters are passed in order, they must be received in order. And must call super to call the constructor of the parent class.

    1
    2
    3
    4
    5
    class Student extend Person {
    constructor (name, age, grade) {
    super (name, age) //Note here that super must be placed at the top of the constructor.
    this.grade=grade
    }}


  1. Summary

    1. The constructor in the class does not have to be written. It is only written when some initialization operations are to be performed on the instance, such as adding specified attributes.

    2. If class a inherits class b, and a constructor is written in class a, super must be called in the constructor of class a.

    3. The method defined in the class is placed on the prototype object of the class for use by the instance.


  2. Object related knowledge

    All property names in the object are strings (that is, hard-coded), namely this.setState({dataType: event.target.value}) and this.setState({'dataType': event.target.value} ) is the same effect, just shorthand.

    If you want dataType to become a variable, you must write it as [dataType].


    If you want to get the object key name in the object, if the key name is still a variable, you need to use obj[key] to get it instead of obj.[key].

    Such as let a='name'; let obj={}; To get the result of name: 'tom', you must write obj[a] = 'tom'.


Share