Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of class in JavaScript and TypeScript

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of class in JavaScript and TypeScript, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

1. Static members

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

2. Private members

Generally speaking, the members within the class cannot be inherited and can only be used internally, and the instance cannot be accessed. It is a little like the variables inside the closure, but there is still a certain difference. Currently, JavaScript cannot directly define private members and can only be implemented in other ways.

3 、 getter/setter

Accessor properties, when we access or modify the properties of an instance, we can intercept these two operations through accessor properties and do something else. Vue uses this api to track data changes.

4. Instance members

Refers to the members of the instance out of new, which can be inherited, and the reuse of code is realized through this feature.

5. Abstract classes, abstract methods

An abstract class refers to a class that cannot be instantiated. It will report an error when called by the new keyword, and is generally designed as a parent class.

Abstract methods, which only provide the name, parameters and return values of the method, are not responsible for implementation, and the concrete implementation is completed by the subclass. if a subclass inherits from the abstract class, then the subclass must implement all the abstract methods of the parent class, otherwise it will report an error.

Neither of these concepts can be implemented directly in JavaScript, but they can be easily implemented in TypeScript or other object-oriented languages, and this feature is also an important means of implementing polymorphism.

Case introduction

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

Person has three properties: name, age, gender, sayHello method and fullName accessor property. At the same time, Person also has some static and private members, so it's too hard to think of examples, so use foo, bar, x, y, z instead.

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

Chinese has a kungfu attribute and can learn martial arts martial.

American has twitter and sendTwitter.

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

Class in JavaScript

To separate the class in JavaScript, two keywords class and extends are provided in ES6, although they are only syntax sugar, the bottom layer still uses prototype to achieve inheritance, but it can not be denied that this writing method does make the code clearer and easier to read.

Class in ES6

Class Person {/ / # x = 'private attribute x attribute; / / static x =' static attribute x attribute; / / name; / / age; / / gender; / / the above writing is still in the proposal and has not become a formal standard, but the possibility of change is slim. / / by the way, using # for private members is really speechless. / * static method of Person, which can be inherited by subclass * can access static member through this * / static foo () {console.log (`class ${this.name} has a ${this.x}`);} constructor (name, age, gender) {this.name = name; this.age = age; this.gender = gender } / * data store, which can access instance members, and instances of subclasses can inherit * to access instance members through this * / get fullName () {const suffix = this.gender = = 'male'? 'Sir': 'madam'; return this.name + suffix;} set fullName (value) {console.log (`you have changed your name to ${value} `);} / * * the instance method of Person, which can be inherited by the instance of subclass * instance member can be accessed through this * / sayHello () {console.log (`Hello, I am ${this.fullName}, I am ${this.age}`) }} Person.x = 'static attribute xaccountclass Chinese extends Person {static bar () {console.log (parent of class ${this.name} is ${super.name} `); super.foo ();} constructor (name, age, gender, kungfu) {super (name, age, gender); this.kungfu = kungfu;} martial () {console.log (` ${this.name} is working on ${this.kungfu} `) }} class American extends Person {/ / static y = 'static attribute y'; static bar () {console.log (class ${this.name} has its own ${this.y} and inherits ${super.x} `of parent class ${super.name});} constructor (name, age, gender, twitter) {super (name, age, gender); this.twitter = twitter;} sendTwitter (msg) {console.log (` ${this.name}: `) Console.log (`${msg}`);}} American.y = 'static attribute yearly property Person.x; / static attribute xPerson.foo (); / / class Person has a static attribute xChinese.x; / / static attribute xChinese.foo (); / / class Chinese has a static attribute xChinese.bar (); / / the parent class of class Chinese is PersonAmerican.x; / / static attribute xAmerican.y / / 'static attribute yAmerican.foo (); / / Class American has a static attribute xAmerican.bar (); / / Class American has its own static attribute y and inherits the static attribute xconst p = new Person (' Lucy', 20, 'female') of the parent class Person; const c = new Chinese ('Han Meimei', 18, 'female', 'Wing Chun Boxing') Const a = new American ('Trump', 72, 'male', 'Donald J. Trump'); c.sayHello (); / Hello I am Ms. Han Meimei, I am 18 years old c.martial (); / / Han Meimei is practicing Yongchun Boxing a.sayHello (); / / Hello, I am Mr. Trump, I am 72 years old a.sendTwitter (' Twitter Rule'); / / Trump: Twitter governing the country

Class before ES6

The essence of ES5 inheritance is to create the instance object this of the subclass first.

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

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

Then modify the this with the constructor of the subclass.

To implement inheritance, we need to first implement an extendsClass function that makes the subclass inherit the static and instance members of the parent class.

Function extendsClass (parent, child) {/ / prevent members of the same name as the parent class from being overwritten by the parent class var flag = false; / / inherit static member for (var k in parent) {flag = k in child; if (! flag) {child [k] = parent [k] }} / inherit members on parent class prototype / / cut off data sharing between parent and subclasses with a new constructor 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; / / if you write getter/setter in prototype, you won't get Object.defineProperty (this, 'fullName', {get: function () {var suffix = this.gender = =' male'? 'Mr.':'Ma'am'; return this.name + suffix;}, set: function () {console.log ('you have changed your name to' + value +');},});} Person.x = 'static attribute x' this.name 'Person.Foo = function () {console.log (' class'+ this.name + 'has a' + this.x) } Person.prototype = {constructor: Person, / / get fullName () {}, / / set fullName (value) {}, sayHello: function () {console.log ('Hello I am' + this.fullName +', I'+ this.age +');},}; function Chinese (name, age, gender, kungfu) {/ / change this direction with call to inherit the instance properties of the parent class Person.call (this, name, age, gender) This.kungfu = kungfu;} Chinese.bar = function () {console.log (the parent of 'class' + this.name +'is'+ Person.name); Person.foo ();} Chinese.prototype = {constructor: Chinese, martial: function () {console.log (this.name + 'being trained' + this.kungfu +');}}; extendsClass (Person, Chinese); function American (name, age, gender, twitter) {Person.call (this, name, age, gender) This.twitter = twitter;} American.y = 'static attribute yawnscape American.bar = function () {console.log (class' + this.name + 'has its own' + this.y + 'and inherits parent class' + Person.name +');} American.prototype = {constructor: American, sendTwitter: function (msg) {console.log (this.name +':'); console.log (''+ msg);}} ExtendsClass (Person, American)

Class in TypeScript

After talking about the classes in JavaScript, we still don't use the three concepts of abstract class, abstract method and private method. Because of the limitation of JavaScript language, it is very difficult to realize these three concepts, but it is easy to implement this feature in TypeScript.

First of all, let's modify the description in the example slightly. Person is an abstract class, because a normal person must have a nationality, and the sayHello method of Person is an abstract method, because each country greets each other differently. The gender of the other person can only be read and cannot be modified, and it is certain that it is either a boy or a girl, so we have to use enumeration.

Enum Gender {female = 0, male = 1}; abstract class Person {private x: string = 'private attribute x, subclasses and instances cannot be accessed'; protected y: string = 'private attribute y, subclasses can be accessed, but instances cannot be accessed'; name: string; public age: number; public readonly gender: Gender; / / indicates that this is a read-only attribute public static x: string = 'static attribute x' with the keyword readonly Public static foo () {console.log (class ${this.name} has a ${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? 'Mr': 'madam'; return this.name + suffix;} set FullName (value: string) {console.log (`you have changed your name to ${value} `);} / / Abstract method. The concrete implementation is left to the subclass to complete abstract sayHello (): void;} class Chinese extends Person {public kungfu: string; public static bar () {console.log (the parent of the` class ${this.name} is ${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 (`Hello, I am ${this.fullName}, I am ${this.age} `);} public martial () {console.log (` ${this.name} is working on ${this.kungfu} `);} class American extends Person {static y = 'static attribute y' Public static bar () {console.log (`class ${this.name} has its own ${this.y} and inherits ${super.x}` of parent class ${super.name});} 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}, Ichimm ${this.age} years old`);} public sendTwitter (msg: string): void {console.log (` ${this.name}: `); console.log (` ${msg} `);}} Person.x; / static attribute xPerson.foo (); / / Class Person has a static attribute xChinese.x / / static attribute xChinese.foo (); / / Class Chinese has a static attribute xChinese.bar (); / / the parent class of class Chinese is PersonAmerican.x; / / static attribute xAmerican.y; / / 'static attribute yAmerican.foo (); / / Class American has a static attribute xAmerican.bar () / the class American has its own static attribute y and inherits the static attribute xconst c of the parent class Person: Chinese = new Chinese ('Han Meimei', 18, Gender.female, 'Wing Chun Quan'); const a: American = new American ('Trump', 72, Gender.male, 'Donald J. Trump'); c.sayHello (); / / Hello, I am Ms. Han Meimei, I am 18 years old c.martial () / / Han Meimei is practicing Yongchun boxing a.sayHello (); / / Hello, I am Mr. Trump, Ithumm 72 years olda.sendTwitter ('governing the country') / / Trump: thank you for reading this article carefully. I hope the article "sample Analysis of class in JavaScript and TypeScript" shared by the editor will be helpful to you. At the same time, I hope you will support us and follow the industry information channel. More related knowledge is waiting for you to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report