React学习笔记二:基础知识(2)

113 阅读2分钟
5.1 类的定义
class Person{
    // 可以直接在类中定义属性zhong
    name = '孙悟空';
    age = 18;

    // 构造函数
    // 当我们通过new创建对象时,实际上就是在调用类中的构造函数
    constructor(){
        console.log('我执行了');
    };

    // 定义实例方法
    run(){
        console.log('我会跑');
    }
}
const per = new Person(); // 由于这里通过new创建对象,所以此处 打印:我执行了;
const per2 = new Person(); // 同上 ↑

console.log(per); // Person {name: '孙悟空', age: 18}
console.log(per2); // Person {name: '孙悟空', age: 18}

per.run() // 我会跑
new Person()  // 我执行了


class MyClass{
    constructor(...args){
        console.log(args);
    }
}
new MyClass(1,2,3,4,5) // [1,2,3,4,5]


class Person1{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
}
const per1 = new Person1('孙悟空', 18)
console.log(per1);  // Person1 {name: '孙悟空', age: 18}
5.2 类的this
// 类中的所有代码自动开启严格模式,都会在严格模式下执行
// 严格模式("use strict")下其中一个特点是;函数的this不再是window,而是undefined
// 箭头函数中没有arguments
// 不能作为构造函数调用
// 无法通过call、apply、bind指定函数的this

// 注意:
// 在类中方法的this不是固定的
    // 以方法形式调用时,this就是当前实例
    // 以函数形式调用,this是undefined
// 在开发中,有些情况下我们希望this是固定的,不会因为调用方式不同而改变
    // 如果遇到上述需求可以使用箭头函数来定义类中的方法
    // 如果类中方法使用箭头函数来定义,则方法中的this恒为当前实例
class MyClass{
    // 普通函数
    fn(){
        console.log(this);
    }
    
    // 箭头函数
    fn = () => {
        console.log(this)
    }
}

// 类中方法为普通函数时 ↓↓↓↓↓
const mc = new MyClass()
mc.fn() // MyClass {}

const test = mc.fn;
test()  // undefined

// 类中方法为箭头函数时 ↓↓↓↓↓
const mc = new MyClass()
mc.fn() // MyClass {fn: ƒ} 

const test = mc.fn;
test()  // MyClass {fn: ƒ} 

// 绑定方法的this
class MyClass{
    constructor(){
        this.fn = this.fn.bind(this)
    }
    
}
5.3 类的继承
// 将多个类中的重复代码提取出来
class Animal{
    constructor(name,age){
        this.name = name
        this.age = age
    }
    sayHello = () => {
        console.log('动物在叫~');
    }
}

// 通过继承可以使类中拥有其他类中的属性和方法
// 使用extends来继承一个雷,继承后就相当于降该类的代码复制到当前类中
// 当我们使用继承后,被继承的类就称为父类,继承父类的类称为子类

// 子类继承父类后将获得父类中所有的属性和方法
class Dog extends Animal {
// constructor(name,age){
//   this.name = name
//   this.age = age
// }

    // 重写父类方法
    sayHello = () => {
        console.log('wang wang wang ~');
    }
}

const dog = new Dog('旺财', 5)
console.log(dog.name, dog.age); // 旺财 5
dog.sayHello()  // wang wang wang ~

class Snake extends Animal {
    // 携带父类属性参数
    constructor(name,age,length){
      super(name,age,) // super 放在所有属性前
      this.length = length
    }
    // 重写父类方法
    sayHello = () => {
      console.log('si si si ~');
    }
}

const snake = new Snake('长虫',3,10)
console.log(snake.name, snake.age, snake.length); // 长虫 3 10
5.4 类的静态属性和方法
// 直接通过类调用的属性和方法称为静态属性和静态方法
class MyClass{
    static name = 'haha'
    static fn = () => {
        console.log('方法');
    }
    static fnThis = () => {
        console.log(this);  // 静态方法this不是实例对象而是当前类对象
    }
}
// 无需实例化,直接调用
console.log(MyClass.name);  // haha
MyClass.fn(); // 方法
MyClass.fnThis() // class MyClass{...}  类自身