Home Web Front-end JS Tutorial How to use JS and TypeScript

How to use JS and TypeScript

Jun 02, 2018 am 11:50 AM
javascript typescript use

This time I will show you how to use JS and TypeScript, and what are the precautions for using 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.

Recently, in the process of learning Angular, 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. 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 = '静态属性x';
 // name;
 // age;
 // gender;
 // 上面的写法还在提案中,并没有成为正式标准,不过变化的可能性已经不大了。
 // 顺便吐槽一下,用 # 表示私有成员,真的是很无语.
 /**
  * Person的静态方法,可以被子类继承
  * 可以通过 this 访问静态成员
  */
 static foo() {
  console.log(`类 ${this.name} 有一个 ${this.x}`);
 }
 constructor(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
 }
 /**
  * 数据存储器,可以访问实例成员,子类的实例可以继承
  * 以通过 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 = '静态属性x';
Copy after login
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} `);
 }
}
Copy after login
class American extends Person {
 // static y = '静态属性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}`);
 }
}
Copy after login
American.y = '静态属性y';
Person.x;  // 静态属性x
Person.foo(); // 类 Person 有一个 静态属性x
Chinese.x;  // 静态属性x
Chinese.foo(); // 类 Chinese 有一个 静态属性x
Chinese.bar(); // 类 Chinese 的父类是 Person
American.x;  // 静态属性x
American.y;  // '静态属性y
American.foo(); // 类 American 有一个 静态属性x
American.bar(); // 类 American 有自己的 静态属性y ,还继承了父类 Person 的 静态属性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('推特治国'); // 特朗普 : 推特治国
Copy after login

The inheritance of class

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

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

ES6 的继承机制完全不同,实质是先创造父类的实例对象 this,所以必须先调用 super 方法,

然后再用子类的构造函数修改this。

为了实现继承,我们需要先实现一个 extendsClass 函数,它的作用是让子类继承父类的静态成员和实例成员。

function extendsClass(parent, child) {
 // 防止子类和父类相同名称的成员被父类覆盖
 var flag = false;
 // 继承静态成员
 for (var k in parent) {
  flag = k in child;
  if (!flag) {
   child[k] = parent[k];
  }
 }
 // 继承父类prototype上的成员
 // 用一个新的构造函数切断父类和子类之间的数据共享
 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];
  }
 }
}
Copy after login
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 = '静态属性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 + ' 了');
 },
};
Copy after login
function Chinese(name, age, gender, kungfu) {
 // 用call改变this指向,实现继承父类的实例属性
 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);
Copy after login
function American(name, age, gender, twitter) {
 Person.call(this, name, age, gender);
 this.twitter = twitter;
}
American.y = '静态属性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);
Copy after login

TypeScript 中的 class

讲完了 JavaScript 中的类,还是没有用到 抽象类,抽象方法,私有方法这三个概念,由于 JavaScript 语言的局限性,想要实现这三种概念是很困难的,但是在 TypeScript 可以轻松的实现这一特性。

首先我们稍微修改一下例子中的描述,Person 是抽象类,因为一个正常的人肯定是有国籍的,Person 的 sayHello 方法是抽象方法,因为每个国家打招呼的方式不一样。另外一个人的性别是只能读取,不能修改的,且是确定的是,不是男生就是女生,所以还要借助一下枚举。

enum Gender {
 female = 0,
 male = 1
};
Copy after login
abstract class Person {
 private x: string = '私有属性x,子类和实例都无法访问';
 protected y: string = '私有属性y,子类可以访问,实例无法访问';
 name: string;
 public age: number;
 public readonly gender: Gender; // 用关键字 readonly 表明这是一个只读属性
 public static x: string = '静态属性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} `);
 }
 // 抽象方法,具体实现交由子类完成
 abstract sayHello(): void;
}
Copy after login
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} `);
 }
}
Copy after login
class American extends Person {
 static y = '静态属性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}`);
 }
}
Copy after login
Person.x;  // 静态属性x
Person.foo(); // 类 Person 有一个 静态属性x
Chinese.x;  // 静态属性x
Chinese.foo(); // 类 Chinese 有一个 静态属性x
Chinese.bar(); // 类 Chinese 的父类是 Person
American.x;  // 静态属性x
American.y;  // '静态属性y
American.foo(); // 类 American 有一个 静态属性x
American.bar(); // 类 American 有自己的 静态属性y ,还继承了父类 Person 的 静态属性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('推特治国'); // 特朗普 : 推特治国
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样操作vue2.0 移动端实现下拉刷新和上拉加载

怎样使用vue计算属性与方法侦听器

The above is the detailed content of How to use 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

How to use Thunder to download magnet links How to use Thunder to download magnet links Feb 25, 2024 pm 12:51 PM

With the rapid development of network technology, our lives have also been greatly facilitated, one of which is the ability to download and share various resources through the network. In the process of downloading resources, magnet links have become a very common and convenient download method. So, how to use Thunder magnet links? Below, I will give you a detailed introduction. Xunlei is a very popular download tool that supports a variety of download methods, including magnet links. A magnet link can be understood as a download address through which we can obtain relevant information about resources.

How to use Xiaomi Auto app How to use Xiaomi Auto app Apr 01, 2024 pm 09:19 PM

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

See all articles