current position:Home>TS basic knowledge (II)
TS basic knowledge (II)
2021-08-27 06:40:30 【Shanren ll】
This is my participation 8 The fourth of the yuegengwen challenge 21 God , Check out the activity details :8 Yuegengwen challenge
object-oriented
Object oriented is a very important idea in program , It is understood by many students as a difficult , A more profound problem , It's not . Object oriented is simple , In short All operations in the program need to be completed through objects .
-
for instance :
- To operate the browser, use window object
- To operate a web page, use document object
- The operation console shall use console object
All operations must pass through the object , That is, the so-called object-oriented , So what is the object ? This is about what the program is , The essence of computer program is the abstraction of real things , The antonym of abstract is concrete , such as : A photograph is an abstraction of a concrete person , Car model is the abstraction of concrete car, etc . Programs are also abstractions of things , In the program, we can represent a person 、 A dog 、 A gun 、 A bullet and everything . When a thing arrives in a program, it becomes an object .
In the program, all objects are divided into two parts: data and function , Take people for example , The name of the person 、 Gender 、 Age 、 height 、 Weight, etc. are data , People can talk 、 Walk 、 having dinner 、 Sleep is a human function . Data is called an attribute in an object , And functions are called methods . So in short , In a program, everything is an object .
1、 class (class)
To be object-oriented , Action object , The first thing is to have objects , So the next question is how to create objects . To create an object , You must first define the class , The so-called class can be understood as the model of the object , The program can create objects of the specified type according to the class , for instance : Can pass Person Class to create human objects , adopt Dog Class to create a dog object , adopt Car Class to create an object for the car , Different classes can be used to create different objects .
-
Defining classes :
-
class Class name { Property name : type ; constructor( Parameters : type ){ this. Property name = Parameters ; } Method name (){ .... } } Copy code
-
-
Example :
-
class Person{ // Directly defined attribute / Method :L Define instance properties (new After creating the object , Get... Through objects ) name: string; age: number; constructor(name: string, age: number){ this.name = name; this.age = age; } sayHello(){ console.log(` Hello everyone , I am a ${this.name}`); } // Use static Defined attribute / Method It's a static property , You can use the . Direct access } Copy code
-
-
Use class :
-
const p = new Person(' The Monkey King ', 18); p.sayHello(); Copy code
-
2、 The characteristics of object-oriented
-
encapsulation
-
Objects are essentially containers for properties and methods , Its main function is to store properties and methods , This is called encapsulation
-
By default , The properties of an object can be modified arbitrarily , To ensure the security of data , stay TS You can set the permissions of attributes in
-
Read-only property (readonly):
- If you add a... When declaring a property readonly, Then the attribute becomes a read-only attribute and cannot be modified
-
TS Attributes in have three modifiers :
- public( The default value is ), Can be in the class 、 Modify in subclasses and objects
- protected , Can be in the class 、 Modify in subclass
- private , You can modify... In a class
-
Example :
-
public
-
class Person{ public name: string; // Writing or not writing anything is public public age: number; constructor(name: string, age: number){ this.name = name; // You can modify... In a class this.age = age; } sayHello(){ console.log(` Hello everyone , I am a ${this.name}`); } } class Employee extends Person{ // If you write a constructor in a subclass -constructor , Must pass super( Parameters ) Call parent constructor constructor(name: string, age: number){ // super Represents the parent class of the current class super(name, age); this.name = name; // Subclasses can be modified } } const p = new Person(' The Monkey King ', 18); p.name = ' Pig eight quit ';// Can be modified by objects Copy code
-
-
protected
-
class Person{ protected name: string; protected age: number; constructor(name: string, age: number){ this.name = name; // You can modify this.age = age; } sayHello(){ console.log(` Hello everyone , I am a ${this.name}`); } } class Employee extends Person{ constructor(name: string, age: number){ super(name, age); this.name = name; // Subclasses can be modified } } const p = new Person(' The Monkey King ', 18); p.name = ' Pig eight quit ';// Do not modify Copy code
-
-
private
-
class Person{ private name: string; private age: number; constructor(name: string, age: number){ this.name = name; // You can modify this.age = age; } sayHello(){ console.log(` Hello everyone , I am a ${this.name}`); } } class Employee extends Person{ constructor(name: string, age: number){ super(name, age); this.name = name; // Cannot modify in subclass } } const p = new Person(' The Monkey King ', 18); p.name = ' Pig eight quit ';// Do not modify Copy code
-
-
-
Attribute accessor
-
For some Properties that do not want to be arbitrarily modified , You can set it to private
-
Set it directly to private Will lead to You can no longer modify its properties through objects
-
We can define a set of reads in the class 、 How to set properties , The property read or set to the property is called the accessor of the property
-
The method of reading properties is called setter Method , The method of setting properties is called getter Method
-
Example :
-
class Person{ private _name: string; constructor(name: string){ this._name = name; } get name(){ return this._name; } set name(name: string){ this._name = name; } } const p1 = new Person(' The Monkey King '); console.log(p1.name); // adopt getter Read name attribute p1.name = ' Pig eight quit '; // adopt setter modify name attribute Copy code
-
-
-
Static attribute
-
Static attribute ( Method ), Also known as class properties . There is no need to create an instance to use static properties , Through the class, you can directly use
-
Static attribute ( Method ) Use static start
-
Example :
-
class Tools{ static PI = 3.1415926; static sum(num1: number, num2: number){ return num1 + num2 } } console.log(Tools.PI); console.log(Tools.sum(123, 456)); Copy code
-
-
-
this
- In class , Use this Represents the current object
-
-
Inherit
-
Inheritance is another feature of object orientation
-
Through inheritance, you can introduce properties and methods from other classes into the current class
-
Example :
-
class Animal{ name: string; age: number; constructor(name: string, age: number){ this.name = name; this.age = age; } } class Dog extends Animal{ bark(){ console.log(`${this.name} I'm barking !`); } } const dog = new Dog(' Wangcai ', 4); dog.bark(); Copy code
-
-
-
Through inheritance, you can extend the class without modifying the class
-
rewrite
-
When inheritance occurs , If the method in the subclass will replace the method with the same name in the parent class , This is called method rewriting
-
Example :
-
class Animal{ name: string; age: number; constructor(name: string, age: number){ this.name = name; this.age = age; } run(){ console.log(` Parent class run Method !`); } } class Dog extends Animal{ bark(){ console.log(`${this.name} I'm barking !`); } run(){ console.log(` A subclass of run Method , Will override... In the parent class run Method !`); } } const dog = new Dog(' Wangcai ', 4); dog.bark(); Copy code
- Can be used in subclasses super To complete the reference to the parent class
-
-
-
abstract class (abstract class)
- Abstract classes are classes that are specifically used to be inherited by other classes , It can only be inherited by other classes and cannot be used to create instances
-
abstract class Animal{ abstract run(): void; bark(){ console.log(' Animals are barking ~'); } } class Dog extends Animals{ run(){ console.log(' The dog is running ~'); } } Copy code
- Use abstract The first method is called abstract method , Abstract methods have no method body and can only be defined in abstract classes , When inheriting abstract classes, abstract methods must implement
-
copyright notice
author[Shanren ll],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827064026830V.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich