<acronym id="s8ci2"><small id="s8ci2"></small></acronym>
<rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
<acronym id="s8ci2"></acronym>
<acronym id="s8ci2"><center id="s8ci2"></center></acronym>
0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

鴻蒙語言TypeScript學習第16天:【類】

jf_46214456 ? 來源:jf_46214456 ? 作者:jf_46214456 ? 2024-04-15 09:29 ? 次閱讀

1、TypeScript 類

TypeScript 是面向對象的 JavaScript。

類描述了所創建的對象共同的屬性和方法。

TypeScript 支持面向對象的所有特性,比如 類、接口等。

TypeScript 類定義方式如下:

class class_name { 
    // 類作用域
}

定義類的關鍵字為 class,后面緊跟類名,類可以包含以下幾個模塊(類的數據成員):

  • 字段 ? 字段是類里面聲明的變量。字段表示對象的有關數據。
  • 構造函數 ? 類實例化時調用,可以為類的對象分配內存。
  • 方法 ? 方法為對象要執行的操作。

實例

鴻蒙開發文檔參考:[qr23.cn/AKFP8k]

創建一個 Person 類:

TypeScript

class Person { }復制

編譯以上代碼,得到以下 JavaScript 代碼:

JavaScript

var Person = /** @class */ (function () {
    function Person() {
    }
    return Person;
}());復制

2、創建類的數據成員

搜狗高速瀏覽器截圖20240326151547.png

以下實例我們聲明了類 Car,包含字段為 engine,構造函數在類實例化后初始化字段 engine。

this 關鍵字表示當前類實例化的對象。注意構造函數的參數名與字段名相同,this.engine 表示類的字段。

此外我們也在類中定義了一個方法 disp()。

## TypeScript

class Car {
// 字段
engine:string;

// 構造函數 
constructor(engine:string) { 
    this.engine = engine 
}  

// 方法 
disp():void { 
    console.log("發動機為 :   "+this.engine) 
}

}復制

編譯以上代碼,得到以下 JavaScript 代碼:

## JavaScript

var Car = /** @class */ (function () {
// 構造函數
function Car(engine) {
this.engine = engine;
}
// 方法
Car.prototype.disp = function () {
console.log("發動機為 : " + this.engine);
};
return Car;
}());復制

---

## 3、創建實例化對象

我們使用 new 關鍵字來實例化類的對象,語法格式如下:

var object_name = new class_name([ arguments ])

類實例化時會調用構造函數,例如:

var obj = new Car("Engine 1")

類中的字段屬性和方法可以使用 . 號來訪問:

// 訪問屬性
obj.field_name

// 訪問方法
obj.function_name()

### 完整實例

以下實例創建來一個 Car 類,然后通過關鍵字 new 來創建一個對象并訪問屬性和方法:

## TypeScript

class Car {
// 字段
engine:string;

// 構造函數
constructor(engine:string) {
this.engine = engine
}

// 方法
disp():void {
console.log("函數中顯示發動機型號 : "+this.engine)
}
}

// 創建一個對象
var obj = new Car("XXSY1")

// 訪問字段
console.log("讀取發動機型號 : "+obj.engine)

// 訪問方法
obj.disp()復制

編譯以上代碼,得到以下 JavaScript 代碼:

## JavaScript

var Car = /** @class */ (function () {
// 構造函數
function Car(engine) {
this.engine = engine;
}
// 方法
Car.prototype.disp = function () {
console.log("函數中顯示發動機型號 : " + this.engine);
};
return Car;
}());
// 創建一個對象
var obj = new Car("XXSY1");
// 訪問字段
console.log("讀取發動機型號 : " + obj.engine);
// 訪問方法
obj.disp();復制


讀取發動機型號 : XXSY1
函數中顯示發動機型號 : XXSY1

---

## 4、類的繼承

TypeScript 支持繼承類,即我們可以在創建類的時候繼承一個已存在的類,這個已存在的類稱為父類,繼承它的類稱為子類。

類繼承使用關鍵字 extends,子類除了不能繼承父類的私有成員(方法和屬性)和構造函數,其他的都可以繼承。

TypeScript 一次只能繼承一個類,不支持繼承多個類,但 TypeScript 支持多重繼承(A 繼承 B,B 繼承 C)。

語法格式如下:

class child_class_name extends parent_class_name

### 實例

類的繼承:實例中創建了 Shape 類,Circle 類繼承了 Shape 類,Circle 類可以直接使用 Area 屬性:

## TypeScript

class Shape {
Area:number

constructor(a:number) {
this.Area = a
}
}

class Circle extends Shape {
disp():void {
console.log("圓的面積: "+this.Area)
}
}

var obj = new Circle(223);
obj.disp()復制

編譯以上代碼,得到以下 JavaScript 代碼:

## JavaScript

var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ proto: [] } instanceof Array && function (d, b) { d.proto = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (
.prototype = b.prototype, new __());
};
})();
var Shape = /** @class / (function () {
function Shape(a) {
this.Area = a;
}
return Shape;
}());
var Circle = /
* @class */ (function (_super) {
__extends(Circle, _super);
function Circle() {
return _super !== null && _super.apply(this, arguments) || this;
}
Circle.prototype.disp = function () {
console.log("圓的面積: " + this.Area);
};
return Circle;
}(Shape));
var obj = new Circle(223);
obj.disp();復制

輸出結果為:

圓的面積: 223

需要注意的是子類只能繼承一個父類,TypeScript 不支持繼承多個類,但支持多重繼承,如下實例:

## TypeScript

class Root {
str:string;
}

class Child extends Root {}
class Leaf extends Child {} // 多重繼承,繼承了 Child 和 Root 類

var obj = new Leaf();
obj.str ="hello"
console.log(obj.str)復制

編譯以上代碼,得到以下 JavaScript 代碼:

## JavaScript

var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ proto: [] } instanceof Array && function (d, b) { d.proto = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (
.prototype = b.prototype, new __());
};
})();
var Root = /** @class / (function () {
function Root() {
}
return Root;
}());
var Child = /
* @class / (function (_super) {
__extends(Child, _super);
function Child() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Child;
}(Root));
var Leaf = /
* @class */ (function (_super) {
__extends(Leaf, _super);
function Leaf() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Leaf;
}(Child)); // 多重繼承,繼承了 Child 和 Root 類
var obj = new Leaf();
obj.str = "hello";
console.log(obj.str);復制

輸出結果為:

hello

---

## 5、繼承類的方法重寫

類繼承后,子類可以對父類的方法重新定義,這個過程稱之為方法的重寫。

其中 super 關鍵字是對父類的直接引用,該關鍵字可以引用父類的屬性和方法。

## TypeScript

class PrinterClass {
doPrint():void {
console.log("父類的 doPrint() 方法。")
}
}

class StringPrinter extends PrinterClass {
doPrint():void {
super.doPrint() // 調用父類的函數
console.log("子類的 doPrint()方法。")
}
}復制

編譯以上代碼,得到以下 JavaScript 代碼:

## JavaScript

var obj = new StringPrinter()
obj.doPrint()

var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ proto: [] } instanceof Array && function (d, b) { d.proto = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function () { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (
.prototype = b.prototype, new __());
};
})();
var PrinterClass = /** @class / (function () {
function PrinterClass() {
}
PrinterClass.prototype.doPrint = function () {
console.log("父類的 doPrint() 方法。");
};
return PrinterClass;
}());
var StringPrinter = /
* @class */ (function (_super) {
__extends(StringPrinter, _super);
function StringPrinter() {
return _super !== null && _super.apply(this, arguments) || this;
}
StringPrinter.prototype.doPrint = function () {
_super.prototype.doPrint.call(this); // 調用父類的函數
console.log("子類的 doPrint()方法。");
};
return StringPrinter;
}(PrinterClass));
var obj = new StringPrinter();
obj.doPrint();復制

輸出結果為:

父類的 doPrint() 方法。
子類的 doPrint()方法。

---

## 6、static 關鍵字

static 關鍵字用于定義類的數據成員(屬性和方法)為靜態的,靜態成員可以直接通過類名調用。

## TypeScript

class StaticMem {
static num:number;

static disp():void {
console.log("num 值為 "+ StaticMem.num)
}
}

StaticMem.num = 12 // 初始化靜態變量
StaticMem.disp() // 調用靜態方法復制

編譯以上代碼,得到以下 JavaScript 代碼:

## JavaScript

var StaticMem = /** @class */ (function () {
function StaticMem() {
}
StaticMem.disp = function () {
console.log("num 值為 " + StaticMem.num);
};
return StaticMem;
}());
StaticMem.num = 12; // 初始化靜態變量
StaticMem.disp(); // 調用靜態方法復制

輸出結果為:

num 值為 12

---

## 7、instanceof 運算符

instanceof 運算符用于判斷對象是否是指定的類型,如果是返回 true,否則返回 false。

## TypeScript

class Person{ }
var obj = new Person()
var isPerson = obj instanceof Person;
console.log("obj 對象是 Person 類實例化來的嗎? " + isPerson);復制

編譯以上代碼,得到以下 JavaScript 代碼:

## JavaScript

var Person = /** @class */ (function () {
function Person() {
}
return Person;
}());
var obj = new Person();
var isPerson = obj instanceof Person;
console.log(" obj 對象是 Person 類實例化來的嗎? " + isPerson);復制

輸出結果為:

obj 對象是 Person 類實例化來的嗎? true

---

## 8、訪問控制修飾符

TypeScript 中,可以使用訪問控制符來保護對類、變量、方法和構造方法的訪問。TypeScript 支持 3 種不同的訪問權限。

* **public(默認)** : 公有,可以在任何地方被訪問。
* **protected** : 受保護,可以被其自身以及其子類訪問。
* **private** : 私有,只能被其定義所在的類訪問。

以下實例定義了兩個變量 str1  str2,str1  public,str2  private,實例化后可以訪問 str1,如果要訪問 str2 則會編譯錯誤。

## TypeScript

class Encapsulate {
str1:string = "hello"
private str2:string = "world"
}

var obj = new Encapsulate()
console.log(obj.str1) // 可訪問
console.log(obj.str2) // 編譯錯誤, str2 是私有的復制

---

## 9、類和接口

類可以實現接口,使用關鍵字 implements,并將 interest 字段作為類的屬性使用。

以下實例中 AgriLoan 類實現了 ILoan 接口:

## TypeScript

interface ILoan {
interest:number
}

class AgriLoan implements ILoan {
interest:number
rebate:number

constructor(interest:number,rebate:number) {
this.interest = interest
this.rebate = rebate
}
}

var obj = new AgriLoan(10,1)
console.log("利潤為 : "+obj.interest+",抽成為 : "+obj.rebate )復制

編譯以上代碼,得到以下 JavaScript 代碼:

## JavaScript

ar AgriLoan = /** @class */ (function () {
function AgriLoan(interest, rebate) {
this.interest = interest;
this.rebate = rebate;
}
return AgriLoan;
}());
var obj = new AgriLoan(10, 1);
console.log("利潤為 : " + obj.interest + ",抽成為 : " + obj.rebate);復制

輸出結果為:

利潤為 : 10,抽成為 : 1

審核編輯 黃宇

聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • javascript
    +關注

    關注

    0

    文章

    510

    瀏覽量

    53387
  • 鴻蒙
    +關注

    關注

    55

    文章

    1547

    瀏覽量

    42103
收藏 人收藏

    評論

    相關推薦

    鴻蒙TypeScript入門學習第6天:【條件語句】

    條件語句用于基于不同的條件來執行不同的動作。 TypeScript 條件語句是通過一條或多條語句的執行結果(True 或 False)來決定執行的代碼塊。
    的頭像 發表于 04-01 13:51 ?393次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>TypeScript</b>入門<b class='flag-5'>學習</b>第6天:【條件語句】

    鴻蒙TypeScript學習第7天:【TypeScript 循環】

    有的時候,我們可能需要多次執行同一塊代碼。一般情況下,語句是按順序執行的:函數中的第一個語句先執行,接著是第二個語句,依此類推。 編程語言提供了更為復雜執行路徑的多種控制結構。
    的頭像 發表于 04-02 14:28 ?398次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>TypeScript</b><b class='flag-5'>學習</b>第7天:【<b class='flag-5'>TypeScript</b> 循環】

    鴻蒙TypeScript 開發學習第9天:【TypeScript Number】

    TypeScript 與 JavaScript 類似,支持 Number 對象。 Number 對象是原始數值的包裝對象。
    的頭像 發表于 04-07 18:02 ?417次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>TypeScript</b> 開發<b class='flag-5'>學習</b>第9天:【<b class='flag-5'>TypeScript</b> Number】

    鴻蒙語言ArkTS(更好的生產力與性能)

    ArkTS是鴻蒙生態的應用開發語言 ArkTS提供了聲明式UI范式、狀態管理支持等相應的能力,讓開發者可以以更簡潔、更自然的方式開發應用。 同時,它在保持TypeScript(簡稱TS)基本語法
    發表于 02-17 15:56

    學習鴻蒙背后的價值?星河版開放如何學習?

    現在是2024年,華為在1月18開展了鴻蒙千帆起儀式發布會。宣布了鴻蒙星河版,并對開發者開放申請,此次發布會主要是說明了,鴻蒙已經是全棧自研底座,鴻蒙星河版本的編程
    發表于 02-22 20:55

    21學通C語言

    ` 本帖最后由 zgzzlt 于 2012-8-16 08:41 編輯 21學通C語言`
    發表于 08-15 19:38

    鴻蒙開源后,大家愿意為開源貢獻而學習一個新語言嗎?

    鴻蒙系統要上線了,雖然為國產的系統能上線了很高興,但是想想又要學習一門新的語言還是挺頭疼的,也不知道新語言難不難,方向是什么。
    發表于 09-10 10:42

    【觸覺智能 Purple Pi OH 開發板體驗】二、鴻蒙系統APP應用例程學習HDC使用學習

    兩年開發鴻蒙APP也是使用的這兩種語言進行開發。當下看TypeScript程序還能說勉強看懂,但是當下開發程序就沒那個實力了,需要之后在抽時間學習。技術更新的也確實是快?。。?! 二、天
    發表于 08-31 11:13

    鴻蒙 OS 應用開發初體驗

    Android 基本無差,所以熟悉 Android 開發的同學上手基本沒啥難度。 ArkTS ArkTS 是鴻蒙生態的應用開發語言。它在保持 TypeScript(簡稱 TS)基本語法風格的基礎上
    發表于 11-02 19:38

    要成為鴻蒙開發者,應該學習哪些編程語言

    據了解,鴻蒙系統是基于Linux開發的,源碼是C語言。那么,作為一名開發者,如何幫助鴻蒙系統構建生態呢?在以往安卓、蘋果系統構建過程,有哪些可以值得借鑒的地方呢?要成為鴻蒙開發者,應該
    的頭像 發表于 09-24 12:06 ?1.2w次閱讀

    快速了解TypeScript和JavaScript之間的差異

    如果我們同時考慮兩者 ——TypeScript 與 JavaScript,那么每個 JavaScript 代碼在 TypeScript 中都是有效的。這意味著 TypeScript 是 JavaScript 的超集。
    的頭像 發表于 03-13 10:19 ?611次閱讀

    TypeScript之父也搞大模型:推出TypeChat

    C# 和 TypeScript 之父 Anders Hejlsberg 今天宣布了全新的開源項目 ——TypeChat,它通過 AI 在自然語言和應用程序模式 (application schema),以及 API 之間構建了一座 “橋梁”,能用新穎有趣的方式使用
    的頭像 發表于 07-24 09:27 ?564次閱讀
    <b class='flag-5'>TypeScript</b>之父也搞大模型:推出TypeChat

    鴻蒙開發之ArkTS基礎知識

    一、ArkTS簡介 ArkTS是HarmonyOS優選的主力應用開發語言。它在TypeScript(簡稱TS)的基礎上,匹配了鴻蒙的ArkUI框架,擴展了聲明式UI、狀態管理等相應的能力,讓開
    的頭像 發表于 01-24 16:44 ?530次閱讀
    <b class='flag-5'>鴻蒙</b>開發之ArkTS基礎知識

    鴻蒙TypeScript入門學習第2天【TypeScript安裝】

    本文介紹 TypeScript 環境的安裝。 我們需要使用到 npm 工具安裝,如果你還不了解 npm,可以參考我之前文檔。
    的頭像 發表于 03-27 15:22 ?165次閱讀
    <b class='flag-5'>鴻蒙</b><b class='flag-5'>TypeScript</b>入門<b class='flag-5'>學習</b>第2天【<b class='flag-5'>TypeScript</b>安裝】

    鴻蒙語言TypeScript學習第18天:【泛型】

    泛型(Generics)是一種編程語言特性,允許在定義函數、類、接口等時使用占位符來表示類型,而不是具體的類型。
    的頭像 發表于 04-16 14:56 ?64次閱讀
    <b class='flag-5'>鴻蒙語言</b><b class='flag-5'>TypeScript</b><b class='flag-5'>學習</b>第18天:【泛型】
    亚洲欧美日韩精品久久_久久精品AⅤ无码中文_日本中文字幕有码在线播放_亚洲视频高清不卡在线观看
    <acronym id="s8ci2"><small id="s8ci2"></small></acronym>
    <rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
    <acronym id="s8ci2"></acronym>
    <acronym id="s8ci2"><center id="s8ci2"></center></acronym>