国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial Detailed explanation of the use of classes in js and typescript

Detailed explanation of the use of classes in js and typescript

Apr 27, 2018 am 11:43 AM
class javascript typescript

This time I will bring you a detailed explanation of the use of classes in js and typescript. What are the precautions for using classes in js and typescript. The following is a practical case, let's take a look.

Preface

For a front-end developer, class is rarely used because in JavaScript Most of them are functional programming. When you raise your hand, there is a function, and there is almost no trace of class or new. Therefore Design Pattern is also a shortcoming of most front-end developers.

In the process of learning Angular recently, I discovered that it uses a lot of classes. I have to admire it. Angular is indeed an excellent framework that deserves in-depth study.

This article will briefly introduce classes in JavaScript and TypeScript.

Basic concepts

Before introducing class, some basic concepts should be introduced first.

1. Static members

Members of the class itself can be inherited, but instances cannot be accessed. They are generally found in tool classes, such as the most common $.ajax in the jQuery era, ajax is $ The static method is easy to use, and there is no need to get a new instance through new or function call.

2. Private members

Members within a class generally cannot be inherited and can only be used internally. Instances cannot be accessed. They are a bit like variables inside a closure, but they are still certain. The difference is that currently JavaScript cannot directly define private members and can only assist in implementation through other methods.

3. Getter/setter

Accessor properties. When we access or modify the properties of an instance, we can intercept these two operations through the accessor properties to do some For other things, Vue uses this API to track data changes.

4. Instance members

refers to the members of the instance created by new, which can be inherited. This feature also enables code reuse.

5. Abstract class, abstract method

Abstract class refers to a class that cannot be instantiated. Calling it through the new keyword will report an error. It is generally designed as a parent class.

Abstract method only provides the name, parameters and return value of the method. It is not responsible for implementation. The specific implementation is completed by the subclass. If a subclass inherits from an abstract class, then the subclass must implement the parent class. All abstract methods, otherwise an error will be reported.

Neither of these two concepts can be directly implemented in JavaScript, but they can be easily implemented in TypeScript or other Object-oriented languages. In addition, this feature is also an important means to achieve polymorphism.

Case introduction

In order to better introduce classes, this article will use three classes as examples, namely Person, Chinese, and American . You can quickly know from the words: Person is the parent class (base class), Chinese and American are subclasses (derived classes).

Person has three attributes: name, age, gender, sayHello method and fullName accessor attribute. At the same time, Person also has some static members and private members. Since it is too difficult to think of examples, let’s use foo, bar, x, y, z instead.

As subclasses, Chinese and American inherit the instance members and static members of Person. At the same time, they also have some methods and attributes of their own:

Chinese has the kungfu attribute and can practice martial arts.

American has twitter and can also sendTwitter.

Next we will use JavaScript and TypeScript to implement this case.

Class in JavaScript

Class in JavaScript should be discussed separately. Two keywords, class and extends, are provided in ES6. Although They are just syntactic sugar, and the bottom layer still uses prototype to implement inheritance, but it cannot be denied that this writing method does make the code clearer and easier to read.

Class in ES6

class?Person?{
?//?#x?=?'私有屬性x';
?//?static?x?=?'靜態(tài)屬性x';
?//?name;
?//?age;
?//?gender;
?//?上面的寫法還在提案中,并沒有成為正式標(biāo)準(zhǔn),不過變化的可能性已經(jīng)不大了。
?//?順便吐槽一下,用?#?表示私有成員,真的是很無語.
?/**
??*?Person的靜態(tài)方法,可以被子類繼承
??*?可以通過?this?訪問靜態(tài)成員
??*/
?static?foo()?{
??console.log(`類?${this.name}?有一個?${this.x}`);
?}
?constructor(name,?age,?gender)?{
??this.name?=?name;
??this.age?=?age;
??this.gender?=?gender;
?}
?/**
??*?數(shù)據(jù)存儲器,可以訪問實例成員,子類的實例可以繼承
??*?以通過?this?訪問實例成員
??*/
?get?fullName()?{
??const?suffix?=?this.gender?===?'男'???'先生'?:?'女士';
??return?this.name?+?suffix;
?}
?set?fullName(value)?{
??console.log(`你已改名為?${value}?`);
?}
?/**
??*?Person的實例方法,可以被子類的實例繼承
??*?可以通過?this?訪問實例成員
??*/
?sayHello()?{
??console.log(`你好我是?${this.fullName}?,我?${this.age}?歲了`);
?}
}
Person.x?=?'靜態(tài)屬性x';
class?Chinese?extends?Person?{
?static?bar()?{
??console.log(`類?${this.name}?的父類是?${super.name}`);
??super.foo();
?}
?constructor(name,?age,?gender,?kungfu)?{
??super(name,?age,?gender);
??this.kungfu?=?kungfu;
?}
?martial()?{
??console.log(`${this.name}?正在修煉?${this.kungfu}?`);
?}
}
class?American?extends?Person?{
?//?static?y?=?'靜態(tài)屬性y';
?static?bar()?{
??console.log(`類?${this.name}?有自己的?${this.y}?,還繼承了父類?${super.name}?的?${super.x}`);
?}
?constructor(name,?age,?gender,?twitter)?{
??super(name,?age,?gender);
??this.twitter?=?twitter;
?}
?sendTwitter(msg)?{
??console.log(`${this.name}?:?`);
??console.log(`?${msg}`);
?}
}
American.y?=?'靜態(tài)屬性y';
Person.x;??//?靜態(tài)屬性x
Person.foo();?//?類?Person?有一個?靜態(tài)屬性x
Chinese.x;??//?靜態(tài)屬性x
Chinese.foo();?//?類?Chinese?有一個?靜態(tài)屬性x
Chinese.bar();?//?類?Chinese?的父類是?Person
American.x;??//?靜態(tài)屬性x
American.y;??//?'靜態(tài)屬性y
American.foo();?//?類?American?有一個?靜態(tài)屬性x
American.bar();?//?類?American?有自己的?靜態(tài)屬性y?,還繼承了父類?Person?的?靜態(tài)屬性x
const?p?=?new?Person('Lucy',?20,?'女');
const?c?=?new?Chinese('韓梅梅',?18,?'女',?'詠春拳');
const?a?=?new?American('特朗普',?72,?'男',?'Donald?J.?Trump');
c.sayHello();?//?你好我是?韓梅梅女士?,我?18?歲了
c.martial();?//?韓梅梅?正在修煉?詠春拳?
a.sayHello();?//?你好我是?特朗普先生?,我?72?歲了
a.sendTwitter('推特治國');?//?特朗普?:?推特治國

The inheritance of class

before ES6 is essentially to create the subclass first Instance object this,

然后再將父類的方法添加到 this 上面 Parent.apply(this) 。

ES6 的繼承機制完全不同,實質(zhì)是先創(chuàng)造父類的實例對象 this,所以必須先調(diào)用 super 方法,

然后再用子類的構(gòu)造函數(shù)修改this。

為了實現(xiàn)繼承,我們需要先實現(xiàn)一個 extendsClass 函數(shù),它的作用是讓子類繼承父類的靜態(tài)成員和實例成員。

function?extendsClass(parent,?child)?{
?//?防止子類和父類相同名稱的成員被父類覆蓋
?var?flag?=?false;
?//?繼承靜態(tài)成員
?for?(var?k?in?parent)?{
??flag?=?k?in?child;
??if?(!flag)?{
???child[k]?=?parent[k];
??}
?}
?//?繼承父類prototype上的成員
?//?用一個新的構(gòu)造函數(shù)切斷父類和子類之間的數(shù)據(jù)共享
?var?F?=?function?()?{?}
?F.prototype?=?parent.prototype;
?var?o?=?new?F();
?for?(var?k?in?o)?{
??flag?=?k?in?child.prototype;
??if?(!flag)?{
???child.prototype[k]?=?o[k];
??}
?}
}
function?Person(name,?age,?gender)?{
?this.name?=?name;
?this.age?=?age;
?this.gender?=?this.gender;
?//?如果將?getter/setter?寫在?prototype?會獲取不到
?Object.defineProperty(this,?'fullName',?{
??get:?function?()?{
???var?suffix?=?this.gender?===?'男'???'先生'?:?'女士';
???return?this.name?+?suffix;
??},
??set:?function?()?{
???console.log('你已改名為?'?+?value?+?'?');
??},
?});
}
Person.x?=?'靜態(tài)屬性x';
Person.foo?=?function?()?{
?console.log('類?'?+?this.name?+?'?有一個?'?+?this.x);
}
Person.prototype?=?{
?constructor:?Person,
?//?get?fullName()?{?},
?//?set?fullName(value)?{?},
?sayHello:?function?()?{
??console.log('你好我是?'?+?this.fullName?+?'?,我?'?+?this.age?+?'?了');
?},
};
function?Chinese(name,?age,?gender,?kungfu)?{
?//?用call改變this指向,實現(xiàn)繼承父類的實例屬性
?Person.call(this,?name,?age,?gender);
?this.kungfu?=?kungfu;
}
Chinese.bar?=?function?()?{
?console.log('類?'?+?this.name?+?'?的父類是?'?+?Person.name);
?Person.foo();
}
Chinese.prototype?=?{
?constructor:?Chinese,
?martial:?function?()?{
??console.log(this.name?+?'?正在修煉?'?+?this.kungfu?+?'?');
?}
};
extendsClass(Person,?Chinese);
function?American(name,?age,?gender,?twitter)?{
?Person.call(this,?name,?age,?gender);
?this.twitter?=?twitter;
}
American.y?=?'靜態(tài)屬性y';
American.bar?=?function?()?{
?console.log('類?'?+?this.name?+?'?有自己的?'?+?this.y?+?'?,還繼承了父類?'?+?Person.name?+?'?的?'?+?Person.x);
}
American.prototype?=?{
?constructor:?American,
?sendTwitter:?function?(msg)?{
??console.log(this.name?+?'?:?');
??console.log('?'?+?msg);
?}
};
extendsClass(Person,?American);

TypeScript 中的 class

講完了 JavaScript 中的類,還是沒有用到 抽象類,抽象方法,私有方法這三個概念,由于 JavaScript 語言的局限性,想要實現(xiàn)這三種概念是很困難的,但是在 TypeScript 可以輕松的實現(xiàn)這一特性。

首先我們稍微修改一下例子中的描述,Person 是抽象類,因為一個正常的人肯定是有國籍的,Person 的 sayHello 方法是抽象方法,因為每個國家打招呼的方式不一樣。另外一個人的性別是只能讀取,不能修改的,且是確定的是,不是男生就是女生,所以還要借助一下枚舉。

enum?Gender?{
?female?=?0,
?male?=?1
};
abstract?class?Person?{
?private?x:?string?=?'私有屬性x,子類和實例都無法訪問';
?protected?y:?string?=?'私有屬性y,子類可以訪問,實例無法訪問';
?name:?string;
?public?age:?number;
?public?readonly?gender:?Gender;?//?用關(guān)鍵字?readonly?表明這是一個只讀屬性
?public?static?x:?string?=?'靜態(tài)屬性x';
?public?static?foo()?{
??console.log(`類?${this.name}?有一個?${this.x}`);
?}
?constructor(name:?string,?age:?number,?gender:?Gender)?{
??this.name?=?name;
??this.age?=?age;
??this.gender?=?gender;
?}
?get?fullName():?string?{
??const?suffix?=?this.gender?===?1???'先生'?:?'女士';
??return?this.name?+?suffix;
?}
?set?FullName(value:?string)?{
??console.log(`你已改名為?${value}?`);
?}
?//?抽象方法,具體實現(xiàn)交由子類完成
?abstract?sayHello():?void;
}
class?Chinese?extends?Person?{
?public?kungfu:?string;
?public?static?bar()?{
??console.log(`類?${this.name}?的父類是?${super.name}`);
??super.foo();
?}
?public?constructor(name:?string,?age:?number,?gender:?Gender,?kungfu:?string)?{
??super(name,?age,?gender);
??this.kungfu?=?kungfu;
?}
?public?sayHello():?void?{
??console.log(`你好我是?${this.fullName}?,我?${this.age}?歲了`);
?}
?public?martial()?{
??console.log(`${this.name}?正在修煉?${this.kungfu}?`);
?}
}
class?American?extends?Person?{
?static?y?=?'靜態(tài)屬性y';
?public?static?bar()?{
??console.log(`類?${this.name}?有自己的?${this.y}?,還繼承了父類?${super.name}?的?${super.x}`);
?}
?public?twitter:?string;
?public?constructor(name:?string,?age:?number,?gender:?Gender,?twitter:?string)?{
??super(name,?age,?gender);
??this.twitter?=?twitter;
?}
?public?sayHello():?void?{
??console.log(`Hello,?I?am?${this.fullName}?,?I'm?${this.age}?years?old`);
?}
?public?sendTwitter(msg:?string):?void?{
??console.log(`${this.name}?:?`);
??console.log(`?${msg}`);
?}
}
Person.x;??//?靜態(tài)屬性x
Person.foo();?//?類?Person?有一個?靜態(tài)屬性x
Chinese.x;??//?靜態(tài)屬性x
Chinese.foo();?//?類?Chinese?有一個?靜態(tài)屬性x
Chinese.bar();?//?類?Chinese?的父類是?Person
American.x;??//?靜態(tài)屬性x
American.y;??//?'靜態(tài)屬性y
American.foo();?//?類?American?有一個?靜態(tài)屬性x
American.bar();?//?類?American?有自己的?靜態(tài)屬性y?,還繼承了父類?Person?的?靜態(tài)屬性x
const?c:?Chinese?=?new?Chinese('韓梅梅',?18,?Gender.female,?'詠春拳');
const?a:?American?=?new?American('特朗普',?72,?Gender.male,?'Donald?J.?Trump');
c.sayHello();?//?你好我是?韓梅梅女士?,我?18?歲了
c.martial();?//?韓梅梅?正在修煉?詠春拳?
a.sayHello();?//?Hello,?I?am?特朗普先生?,?I'm?72?years?old
a.sendTwitter('推特治國');?//?特朗普?:?推特治國

相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注php中文網(wǎng)其它相關(guān)文章!

推薦閱讀:

JS變量聲明var,let.const使用詳解

Vue組件實現(xiàn)簡單彈窗功能案例詳解

The above is the detailed content of Detailed explanation of the use of classes in js and typescript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Replace the class name of an element using jQuery Replace the class name of an element using jQuery Feb 24, 2024 pm 11:03 PM

jQuery is a classic JavaScript library that is widely used in web development. It simplifies operations such as handling events, manipulating DOM elements, and performing animations on web pages. When using jQuery, you often encounter situations where you need to replace the class name of an element. This article will introduce some practical methods and specific code examples. 1. Use the removeClass() and addClass() methods jQuery provides the removeClass() method for deletion

Detailed explanation of PHP Class usage: Make your code clearer and easier to read Detailed explanation of PHP Class usage: Make your code clearer and easier to read Mar 10, 2024 pm 12:03 PM

When writing PHP code, using classes is a very common practice. By using classes, we can encapsulate related functions and data in a single unit, making the code clearer, easier to read, and easier to maintain. This article will introduce the usage of PHPClass in detail and provide specific code examples to help readers better understand how to apply classes to optimize code in actual projects. 1. Create and use classes In PHP, you can use the keyword class to define a class and define properties and methods in the class.

How to replace class name in jQuery? How to replace class name in jQuery? Feb 25, 2024 pm 11:09 PM

How to use replace class name in jQuery? In front-end development, we often encounter situations where we need to dynamically modify the class name of an element. jQuery is a popular JavaScript library that provides a wealth of DOM manipulation methods, allowing developers to easily manipulate page elements. This article will introduce how to use jQuery to replace the class name of an element, and attach specific code examples. First, we need to introduce the jQuery library. If jQuery has been introduced into the project, you can

JavaScript and WebSocket: Building an efficient real-time search engine JavaScript and WebSocket: Building an efficient real-time search engine Dec 17, 2023 pm 10:13 PM

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

See all articles