Properties of encapsulation

During class definition, attributes are protected by the private and protected modifiers to ensure the security of special data. There are also attributes that are encapsulated to ensure that attributes of the private type are accessed or modified in subtypes.

Property modifier

The modifier role
Private (private attributes) Attributes can only be modified/accessed inside the class
Public (Public attribute (The default value)) Attributes can only be modified/accessed inside the class
Protected (Protected type attributes) Properties can only be accessed in the current class and subclasses of the current class

Tips: Public type attributes are not described in this article

Private Attribute type Eg
  • Private disables external access to this property
Class person {// ts add modifier name:string; private age:number; constructor(name:string,age:number){ this.name=name; This.age =age}} const person1=new person('liy',21) console.log(per.age) Per.age =18 // The error property "age" is private and can only be accessed from class "person" ** Private turns off external access to this property **Copy the code
  • Use property encapsulation (property modification through setter methods, getter property storage) use set getters to make properties more secure
Class person {// ts add modifier name:string; private age:number; constructor(name:string,age:number){ this.name=name; Age =age} // define a method to getAge getAge(){return this.age} // define a set method setAge(val:number){// determine whether age is appropriate to avoid unsafe data val>=0? this.age=val:'' } }Copy the code
Protected Property type Eg

Protected properties are accessible only in the current class and subclasses of the current class

Class A{constructor(public name:string,protected Number :number){}} Class B extends A{ test(){ console.log(this.number) } }Copy the code

The generic

Generics is the property of defining functions, interfaces, or classes without specifying a specific type in advance, but specifying the type at the time of use. Usually used when defining a function or class and encountering type ambiguity

Function fn1< k >(a: k): k {return a} // Specify generic type let result = fn1<string>('hello'); // Type inference generic type let result1 = fn1(10);Copy the code
  • Multiple generics can be defined simultaneously

Function fn3<t,k>(a:t,b:k):t{return a}

  • Generic classes can be specified to belong to fixed types
interface face{
  length:'number'

}
function fn4< T extends face>(a:T):T{
  return a
}
Copy the code