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.
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 = '静态属性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';
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 = '静态属性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 = '静态属性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('推特治国'); // 特朗普 : 推特治国
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]; } } }
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 + ' 了'); }, };
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);
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);
TypeScript 中的 class
讲完了 JavaScript 中的类,还是没有用到 抽象类,抽象方法,私有方法这三个概念,由于 JavaScript 语言的局限性,想要实现这三种概念是很困难的,但是在 TypeScript 可以轻松的实现这一特性。
首先我们稍微修改一下例子中的描述,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; // 用关键字 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; }
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 = '静态属性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; // 静态属性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('推特治国'); // 特朗普 : 推特治国
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools
