Home  >  Article  >  Web Front-end  >  How to use classes in JS+TypeScript

How to use classes in JS+TypeScript

php中世界最好的语言
php中世界最好的语言Original
2018-06-06 14:55:311391browse

This time I will show you how to use classes in JS TypeScript, and what are the precautions for using classes in JS TypeScript. The following is a practical case, let's take a look.

Preface

For a front-end developer, classes are rarely used because JavaScript is more about functional programming. , raising your hand is just 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. 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,

Then add the parent class method to this above Parent.apply(this).

The inheritance mechanism of ES6 is completely different. The essence is to first create the instance object this of the parent class, so the super method must be called first,

and then use the constructor of the subclass to modify 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中文网其它相关文章!

推荐阅读:

从零开始使用vue-devtools

vue计算属性与侦听器实战项目详解

The above is the detailed content of How to use classes in JS+TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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