欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

ES6中类和对象的代码示例

程序员文章站 2022-04-26 20:36:25
...
本篇文章给大家带来的内容是关于ES6中类和对象的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

1.基本定义和生成实例

{
    class Parent {
        constructor(name = 'haha') {
            this.name = name;
        }
    }
    let parent = new Parent('v');
    console.log('构造函数和实例', parent); // Parent {name: "v"}
}

2.继承

{
    class Parent {
        constructor(name = 'haha') {
            this.name = name;
        }
    }
    class Child extends Parent {

    }
    console.log('继承', new Child()); // Child {name: "haha"}
}

3.继承传递参数

{
    class Parent {
        constructor(name = 'haha') {
            this.name = name;
        }
    }
    class Child extends Parent {
        constructor(name = 'child') {
            // super()方法,用来解决 继承怎么传递参数(怎么覆盖父类的参数)
            // super的参数列表就是父类构造函数的参数列表,如果参数为空,就采用父类的参数默认值
            super(name); // super必须放在构造函数第一行
            this.type = 'child';
        }
    }
    console.log('继承传递参数', new Child('hello')); // Child {name: "hello", type: "child"}
}

4.getter setter

{
    class Parent {
        constructor(name = 'haha') {
            this.name = name;
        }
        // longName 是一个属性,不是方法
        get longName() {
            return 'lu-' + this.name;
        }
        // longName 是一个属性,不是方法
        set longName(value) {
            this.name = value;
        }
    }
    let person = new Parent();
    console.log('getter', person.longName); // lu-haha
    person.longName = 'hello';
    console.log('setter', person.longName); // lu-hello
}

5.静态方法

{
    class Parent {
        constructor(name = 'haha') {
            this.name = name;
        }
        // static 关键字用来定义静态方法
        static tell() {
            console.log('do tell');
        }
    }
    // 静态方法,直接通过类去调用,不是通过实例
    Parent.tell(); // do tell
}

6.静态属性

{
    class Parent {
        constructor(name = 'haha') {
            this.name = name;
        }
    }
    // 直接在类上定义静态属性
    Parent.type = 'test';
    // 读取静态属性时,也是直接拿类读取
    console.log(Parent.type); // test
}

以上就是ES6中类和对象的代码示例的详细内容,更多请关注其它相关文章!