readonly 作用是将数据变为只读选项,仅仅能查看,不能修改。

    1. class Request {
    2. readonly site: string = 'https://www.demo.com/api';
    3. get(url: string) {
    4. console.log(`当前请求的地址是${this.site}${url} `);
    5. return 123;
    6. }
    7. }
    8. const u1 = new Request();
    9. // 在类的外部访问只读属性
    10. console.log(u1.site);
    11. u1.get('/index');

    但是需要注意,可以访问,但是不能修改。
    image.png

    想要修改只读属性,只能在构造函数中进行修改。

    image.png
    readonly 前面也可以加修饰词,例如:
    image.png