Typescript face of the object of the article one

Source: Internet
Author: User
Tags modifier

Object-oriented is a core part of Typescript, where the following seven principles of object-oriented are introduced first:

    • Single principle: A class child is responsible for a duty.
    • The Richter substitution principle: Subclasses can replace their parent classes anywhere.
    • Dependency Inversion principle: code relies on abstract classes rather than on specific classes, programming for interfaces or abstract classes, rather than specific classes.
    • Interface Isolation principle: Provide a single interface as small as possible, instead of providing a large total interface. Exposing behavior allows the following implementation classes to know as little as possible.
    • Dimitri rule: Minimize the coupling between classes and classes.
    • Opening and closing principle: open for expansion, closed for modification
    • Combination/Aggregation Multiplexing principle: use synthesis/aggregation as much as possible to reuse, and use inheritance as little as possible. Principle: An object in one class that has another class.

There is no detailed introduction to the seven principles of the object-oriented Baidu there are many articles in detail, "object-oriented principles of the review", here a brief description of the concept;

Class

Declarations of classes in ES6:

class Demo {    constructor(a, b) {        this.a = a;        this.b = b;    }    print() {        console.log(this.a + ' ' + this.b);    }}

Declarations of classes in typescript:

class Demo {    public a:string;    public b:string;    constructor(a:string, b:string) {        this.a = a;        this.b = b;    }    print() {        console.log(this.a + ' ' + this.b);    }}

According to a single principle, the split thickness of a class is partly the subjective choice of the developer, with examples often encountered by the front end, including name verification, phone verification, digital verification, mail verification, date validation, and so on. Is it better to have these validations handled in a class or is it more appropriate to declare a class individually? Processing in a class causes the reuse rate of the validation method to be low, resulting in code redundancy. Each validation declares a class and feels a lot more. The proposal in "Learning TypeScript" is a validation declaration of a class. The code is as follows:

class Email{    private email:string;    constructor(email:string){        if(this.validateEmail(email)){            this.email=email;        }else{            throw new Error("Invalid email!");        }    }    private validateEmail(email:string):boolean{        var re=/\S+@\S+\.\S+/        return re.test(email);    }    get():string{      return this.email;    }}class Person{    public name:string;    public age:number;    public email:Email;    constructor(name:strng,age:number,email:Email){        this.name=name;        this.age=age;        this.email=email;    }}

This verifies that the message is in the Email validation format.

Inherited

Inheritance in Typescript is implemented in the form of

class Person{    public name:string;    public age:number;    constructor(name:strng,age:number){        this.name=name;        this.age=age;    }    cons(text:string){      console.log(`Hi! ${this.name},${text}`);    }}class Man extends Person{    sex:string;    constructor(name:strng,age:number,sex:string;){        super(name,age)        this.sex=sex    }    cons(text:string){        super.cons(`man,${text}`)    }}let sam = new Person("li lei",12);let tom: Person = new Man("小明",20);

In the example, the derived class contains a constructor that must call Super (), which executes the constructor of the base class. Also, we must call Super () before accessing the properties of this in the constructor. This is an important rule of typescript enforcement. Man inherits the person and overrides the Cons method, which invokes the Cons method of the parent class.

Class Property Permission modifier
    • Public (default) common property: A derived class, an instance object of a class, can be accessed.
class Person{    public name:string;    public age:number;    constructor(name:strng,age:number){        this.name=name;        this.age=age;    }    cons(text:string){      console.log(`Hi! ${this.name},${text}`);    }}
    • Private property: An instance object of a derived class or class cannot be accessed.
class Person{    private name:string;    public age:number;    constructor(name:strng,age:number){        this.name=name;        this.age=age;    }    cons(text:string){      console.log(`Hi! ${this.name},${text}`);    }}new Person("Cat",12).name; // 错误: 'name' 是私有的.
    • Protected protection properties: Derived classes can be accessed, and instance objects of classes cannot be accessed.
class Person{    protected name:string;    public age:number;    constructor(name:strng,age:number){        this.name=name;        this.age=age;    }}class Man extends Person{    sex:string;    constructor(name:strng,age:number,sex:string;){        super(name,age)        this.sex=sex    }    cons(text:string){         console.log(`Hi! ${this.name},${text}`);    }}new Man("Cat",12).name; // 错误,name是保护属性
    • ReadOnly modifier: The READONLY keyword sets the property to read-only.
class Person{    readonly name:string;    public age:number;    constructor(name:strng,age:number){        this.name=name;        this.age=age;    }}let dad =new Person("Cat",12);dad.name = "小明"; // 错误! name 是只读的.
Access device

Typescript supports the interception of access to object members through Getters/setters.

class Person{    private _name:string;    get name():string{        return this._name;    }    set name(name:string){        this._name=name;    }}let man = new Employee();man.name='小明';

Reference Book Documentation:

    • "Learning TypeScript"
    • Typescript Chinese web

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.