In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian introduces in detail "how to define functions and classes in TypeScript", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to define functions and classes in TypeScript" can help you solve your doubts.
Introduction
"Jump": a function is a syntax for defining behavior, but it is actually adding additional functionality to JS. Similarly, you can create named and anonymous functions.
Function add (num1:number,num2:number): number {return num1+num2;} console.log (add (1)); / / 3 let addNum = (num1:number,num2:number): number = > num1+num2; console.log (addNum (1)); / / 3
We can add a type to each parameter and then add a return type to the function itself. TypeScript can automatically infer the return value type from the return statement, so we usually omit it.
In short, the function type consists of two parts: the parameter type and the return value type, both of which need to be fully written when the complete type is written. In fact, you can write parameter types in the form of a parameter list, specifying a name and type for each parameter to increase the readability of the code.
As long as the parameter type matches, it is considered to be a valid function type, regardless of whether the parameter name is correct.
The second part is the return value type. As mentioned earlier, the return value type is a necessary part of the function type, and if the function does not return any value, you must also specify that the return value type is void and cannot be left blank.
If a type is specified on one side of the assignment statement but there is no type on the other side, the TypeScript compiler automatically recognizes the type.
The way function parameters are defined 1. Declare the function parameter function add (num1:number,num2:number) directly: number {return num1 + num2;} add (1); / / 32. Deconstruct the assignment declaration function parameter function add ({num1,num2}: {num1:number,num2:number}): number {return num1 + num2;} add; / / 33. The remaining parameters declare that the function parameter function add (... rest:number []) {return rest.reduce ((pre,cur) = > pre+cur);} add (2 add 3, 4); / / 14 add ("yichuan", 3); / / error, string 4 cannot be used. Nominally declared function parameter type add = (num1:number,num2:number) = > number; interface add {(x _ number rect _ y _ number): number}
Call method:
Let addFun:add= > (num1,num2) = > num1+num2;5. Optional parameter and default parameter function add (num1:number,num2:number,num3?:number): number {return num1 + num2;}
It is obvious: num1 and num2 are the default parameters, and num3 is optional. Keep in mind that the default parameters are in front and the optional parameters are in the back.
This
The problem of this pointing in JS is annoying. The point of this is specified when the function is called, but it is troublesome to understand the context of the function call. Actually, there is not much difference between the two.
Fortunately, TS can inform you of the wrong use of this.
Function overload
Function overloading or method overloading is the ability to create multiple methods with the same name and different numbers or types of parameters.
Function addFun (num1:number,num2:number): number; function addFun (num1:string,num2:string): string; function addFun (num1:string,num2:number): string; function addFun (num1:number,num2:string): string; function addFun (num1:any,num2:any): any {if (typeof num1 = = "string" | | typeof num2 = "string") {return num1.toString () + num2.toString ();} return num1 + num2;} console.log (addFun (1Jue 2))
Bouncing: we can see that most of the library source code is the way to overload the function. Why?
"Jump": this is because after using function overloading, others can know how the function is called as long as they see the function overload declaration.
The way the function is overloaded is that ts looks for the type from the beginning, returns the function type if it matches, and goes to the next one if it doesn't match. Therefore, when defining overloading, be sure to put the most precise definition first. "tips: when maintaining a common component, you can use this method to let consumers and subsequent maintainers quickly know how the function is called."
Class
Bouncing: what's the difference between TS's class and JS?
"Jump": before es6, traditional Javascript needed to use function and prototype chain inheritance to implement reusable components, but this is difficult for programmers who do not understand the principle of JS prototype chain. ES6 introduces the idea of class, which enables programmers to program in an object-oriented way based on classes.
Properties and methods of the class
Bouncing: in an object-oriented programming language, a class can create a blueprint for an object that describes the common properties and methods of the object to be created.
Class Person {/ / instance property name:string; age:number; / Private field # score:number; / / static property static height:number = 180; / / readonly weight:number = 130; / / Constructor constructor (name:string,age:number,score:number) {this.name = name; this.age = age; this.#score = score } / / instance method getName () {return this.name;} / / static method static getAge () {return this.age;}} let person:Person = new Person ("wenbo", 12); console.log (person.getName ()); console.log (Person.height); person.name = "zhaoshun"; console.log (person.getName ()); Person.height = 170; console.log (Person.height); person.weight = 110 Console.log (person.weight)
Instance properties (member properties): the properties defined directly in the class are instance properties, which need to be accessed through the instance of the object.
Static attributes (class attributes): use the static keyword before the properties to define class properties (static properties), which can be accessed directly through the class.
Private fields: add # to the attribute to make it private, which cannot be accessed outside the included class or even detected. Each private property uniquely defines the classes it contains, and you cannot use ts's accessible modifiers (public, private) on private properties.
Constructor (perform initialization): the constructor is called when the object is created, and in the instance method, this represents the current instance. In the constructor, the current object is the currently newly created object, and you can add properties to the newly created object through this.
Instance method (member method): the method defined directly in the class is the instance method, which needs to be called through the instance of the object. In a method, you can use this to represent the object that currently calls the method. Point to whoever calls the method.
Static methods (class methods): use the static keyword before a method to define class methods (static methods), which can be accessed directly through the class.
Inherit
One of the most basic patterns in class-based programming is to allow inheritance to extend existing classes.
Class Animal {move (distanceInMeters: number = 0) {console.log (`Animal moved ${distanceInMeters} m.`);}} class Dog extends Animal {bark () {console.log ('Woof! woofing');}} const dog = new Dog (); dog.bark (); dog.move (10); dog.bark ()
As shown above is the most basic inheritance: the class inherits properties and methods from the base class. Here, Dog is a derived class, which is derived from the Animal base class through the extends keyword. A derived class is usually called a subclass, and a base class is usually called a superclass.
Because Dog inherits the functionality of Animal, we can create an instance of Dog that can bark () and move ().
Public, private and protected modifiers
In TS, you can set modifiers on the properties, methods, and constructors of a class to limit their scope. The default modifier is public, so members defined in the program are freely accessible to the current class and subclasses.
"tip: get into the habit of adding member modifiers when writing classes."
Class Father {/ / Public member public name:string; / / Private member private age:number; / / protected member protected address:string; public constructor (name:string,age:number,address:string) {this.name = name; this.age = age; this.address = address;} public eat (meters:number) {console.log (`${this.name} moved ${meters}`) }} class Son extends Father {constructor () {super ()} test () {console.log (this.name); / / accessible console.log (this.age); / / the attribute "age" is private and can only be accessed in class "Father". Console.log (this.address); / / accessible}} const bigLiu = new Father ("bigLiu", 32, "Chengdu of Sichuan Province"); console.log (bigLiu.name); / / accessible console.log (bigLiu.age); / / attribute "age" is private and can only be accessed in class "Father". The console.log (bigLiu.address); / / attribute "address" is protected and can only be accessed in the class "Father" and its subclasses. Const smallLiu = new Son (); console.log (bigLiu.name); / / accessible console.log (bigLiu.age); / / property "age" is private and can only be accessed in class "Father". The console.log (bigLiu.address); / / attribute "address" is protected and can only be accessed in the class "Father" and its subclasses. Accessor (accessor)
TypeScript supports intercepting access to object members through getters/setters. It can help you effectively control access to object members.
Class Greeter {constructor (message: string) {this.greeting = message;} greeting: string; get hello () {return this.greeting;} set hi (x) {this.greeting = x;}} const x = new Greeter ('eeee') x.hi (' 22'); x.hello ='2' / / error cannot be modified
You are actually using getters/setters to intercept access to object members. The parsed source code is as follows:
Abstract class
The class declared by the declare abstract keyword is called an abstract class. An abstract class cannot be instantiated because it contains one or more abstract methods. The so-called abstract method refers to the method that does not contain a concrete implementation:
Abstract class Person {constructor (public name: string) {} abstract say (words: string): void;} / / Cannot create an instance of an abstract class. (2511) const lolo = new Person (); / / Error
Abstract classes cannot be instantiated directly, we can only instantiate classes that implement all abstract methods. The details are as follows:
Abstract class Person {constructor (public name: string) {} / Abstract method abstract say (words: string): void;} class Developer extends Person {constructor (name: string) {super (name);} say (words: string): void {console.log (`${this.name} says ${words}`);} const lolo = new Developer ("lolo"); lolo.say ("I love ts!"); / / lolo says I love ts! After reading this, the article "how to define functions and classes in TypeScript" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.