[React learning] - basic knowledge of classes (5)

[React learning] - basic knowledge of classes (5)

insert image description here

  <script>
        // 创建一个Person类
        class Person{
    
    
            //构造器方法
            constructor(name,age){
    
    
            this.name=name;
            this.age=age;
            }
            //一般方法
            speak(){
    
    
                //speak方法一般放在哪里?类的原型上,供实例使用
                //通过Person实例调用speak时,speak中的this就是Person实例
                console.log(`我叫${
     
     this.name},今年${
     
     this.age}`);
            }
        }
        //创建一个Person的实例对象
        const p1=new Person('Tom',18)
        const p2=new Person('Jerry',19)
        p1.speak()
        p2.speak()
    
    </script>

insert image description here

Summarize:

  • It is not necessary to write the constructor in the class, but to perform some initialization operations on the instance, such as adding specified attributes.
  • If class A inherits class B, and class A writes a constructor, then super in the constructor of class A must be called
  • The methods defined in the class are still placed on the prototype object of the class for use by the instance
    insert image description here

Guess you like

Origin blog.csdn.net/m0_46374969/article/details/132237246