JavaScript ES6中class的用法

发布时间 2023-04-06 17:38:26作者: 花粉回家

实例代码如下

class Person {
            constructor(name){
                if(!arguments.length){
                    console.log("我是个人")
                } else {
                    console.log(`我是${name}`)
                }
            }
            call(){
                console.log("人能说话")
            }
        }

        class Student extends Person {
            constructor(name){
                if(!arguments.length){
                    super();
                    console.log("我是学生")
                } else {
                    super(name);
                    console.log(`我是${name}`)
                }
            }
            call(){
                super.call()
                console.log("学生能说话")
            }
        }

        new Student().call()
        new Student("李华").call()

结果如下

image

可以看出ES6的class语法糖基本能实现Java中类的所有操作,除了不能对构造函数进行重载,所以我使用if来实现类似功能