• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript Crash Course: Property Access Modifiers

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

There is no other great moment to head into the world of TypeScript instead of right now. Angular is in TypeScript, React is in TypeScript, and even Vue3 is in TypeScript. That means it's a skill we must equip with rather than wait and see.

This is the first post of my own TypeScript crash course, chances that it's your jam, stay tune;)

public, private, protected and readonly access modifier

  • public the default access modifier for properties

  • private lock the properties inside the cage, no one else except the class in where it's defined can access it. But we could approach it in JavaScript runtime, even by valueOf method.

  • protected as the same as private, but open a backdoor for derived class.

  • readonly the properties marked with readonly should be initialized either when declare in no time or inside constructor. But it only works in TypeScript.

    /* compile time */
    class User {
         readonly idCard: string
         constructor(idCard: string) {
             this.idCard = idCard
         }
    }
    
    let user = new User('123')
    user.idCard = '321' // error hint
    
    /* runtime */
    user.idCard = '321'
    console.log(user.idCard) // "321", the value of idCard has been changed.
    
    // solution for real readonly properties
    
    class User {
         readonly idCard: string
         constructor(idCard: string) {
             this.idCard = idCard
             Object.defineProperty(this, 'idCard', { writable: false })
         }
    }
    /* runtime */
    user.idCard = '321' // everything goes well
    console.log(user.idCard) // but it's still "123"
    

Define properties through constructor parameters

It's way too boring to put values into the properties when construct an instance like below

class User {
    private readonly idCard: string
    protected name: string
    age: number

    constructor(idCard: string, name: string, age: number) {
        this.idCard = idCard
        this.name = name
        this.age = age
    }
}

Fortunately, TypeScript has done that for us. When we specify public, private or other access modifiers on the constructor parameters, a corresponding property is created on the class and filled with the value of the parameter. So we could make the previous one much damn shorter like this.

class User {
    constructor(private readonly idCard: string, protected name: string, public age: number) {}
}

Pretty cool yet;)


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
typescript比javascript多的功能发布时间:2022-07-18
下一篇:
TypeScript的高级用法(持续更新)发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap