JavaScript >> Javascript 文檔 >  >> Tags >> class

JavaScript 中的類介紹

JavaScript是一種基於原型的編程語言,JavaScript中的每個對像都繼承了一個隱藏的prototype 可用於擴展屬性和方法的屬性。

ECMAScript 2015 (ES6) 首次在 JavaScript 中引入了類的概念。在面向對象的編程語言中,類是用於創建具有相同類型的屬性和方法的對象的模板。但是,在 JavaScript 中並非如此。

JavaScript 類只不過是現有基於原型的繼承和構造函數的語法糖。

定義一個類

您可以使用 class 在 JavaScript 中定義一個新類 關鍵詞:

class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    greeting() {
        return `Hey ${this.name} 👋`;
    }
}

上面的例子聲明了 User 具有兩個初始屬性的類:nameage .創建 User 的新實例 ,你可以使用 new 關鍵詞:

const alex = new User('Alex Jones', 32);

console.log(alex.greeting()); // Hey Alex Jones 👋

創建新對象時,constructor() new 自動調用方法 關鍵字。

類表達式

就像箭頭函數一樣,類也可以在另一個表達式中定義。類表達式可以命名或命名。

下面是一個未命名類表達式的例子:

const Circle = class {
    constructor(radius, color) {
        this.radius = radius;
        this.color = color;
    }

    area() {
        return Math.PI * this.radius * this.radius;
    }
}

const circle = new Circle(10, 'Blue');

console.log(circle.area()); // 314.1592653589793

如果想引用body裡面的類名,可以定義一個named class expression .該名稱僅在類表達式本身的範圍內可見:

const Animal = class NamedAnimal {
    constructor() {
    }

    whoIsThere() {
        return NamedAnimal.name;
    }
};

const obj = new Animal();

console.log(obj.whoIsThere()); // NamedAnimal

實例方法

您可以使用與對象方法相同的語法創建類方法。方法基本上是在類範圍內定義的函數,該類的每個實例都可以訪問。

例如,在 Circle 上面的類,我們已經定義了一個名為area()的方法 返回圓的面積。

讓我們定義另一個名為 Rectangle 的類 使用名為 area() 的方法 計算並返回矩形的面積:

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

const rect = new Rectangle(15, 20);

console.log(rect.area()); // 300

靜態方法

靜態方法是在類中定義的函數,無需創建該類的新對象即可訪問。

由於靜態方法是在類級別定義的,所以可以直接使用類名調用。

在 JavaScript 中,您必須使用 static 定義靜態方法的關鍵字:

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    static square(length) {
        return new Rectangle(length, length);
    }
}

const square = Rectangle.square(7);
square.height; // 7
square.width; // 7

getter 和 setter

就像面向對象的類一樣,JavaScript 類也可能包含 getter 和 setter 方法。您可以使用這些方法來格式化和驗證類屬性。

這是 User 的示例 實現 getter 和 setter 的類:

class User {
    constructor(name, age) {
        // Invokes setter methods
        this.name = name;
        this.age = age;
    }

    get name() {
        return this._name;
    }

    set name(value) {
        this._name = value;
    }

    get age() {
        return `${this._name} is ${this._age} years old!`;
    }

    set age(value) {
        if (typeof value !== 'number') {
            throw new Error(`Age must be a number.`);
        }
        this._age = value;
    }
}

const john = new User('John White', 21);

console.log(john.name); // John White
console.log(john.age); // John White is 21 years old!

// Throws an error
const maria = new User('Maria', '32');
// Error: Age must be a number.

注意 age 的 getter 和 setter 方法 財產。我們正在格式化 age 返回之前的值。另外,當 age 已設置,我們確保它是一個數字。當您嘗試時將為 age 設置一個非數字值 屬性,setter方法拋出異常。

計算方法名稱

您還可以使用方括號 [...] 定義計算方法名稱 在 JavaScript 類中:

class User {
    constructor(name) {
        this.name = name;
    }

    ['hi' + 'There']() {
        return ` 👋 ${this.name}`;
    }
}

const alex = new User('Alex');

console.log(alex.hiThere()); //  👋 Alex

繼承

使用類的好處之一是您可以通過基於父類創建新類來輕鬆擴展功能。這使我們可以為其他類似但需要一些額外或更具體功能的對象重用相同的代碼。

當一個 JavaScript 類擴展另一個類時,它會繼承所有靜態和實例方法、getter 和 setter 以及計算屬性。

然後,子類定義了其他方法、靜態、getter 和 setter。它還可以覆蓋父類的方法、靜態、getter 和 setter。

這是 Square 的示例 擴展 Rectangle 功能的類 :

class Rectangle {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

class Square extends Rectangle {
    constructor(length) {
        // `super` refers to the parent class' constructor
        super(length, length);
    }

    inradius() {
        return this.width / 2;
    }
}

const square = new Square(10);

square.area();          // 100 (from Rectangle)
square.inradius();      // 5 (from Square)

查看本文以了解有關 JavaScript 類、對象和原型的更多信息。


Tutorial JavaScript 教程
  1. Cloudflare 頁面的密碼保護

  2. 使用 Redux GET - PUSH

  3. 開始使用 Appwrite 並使用 Appwrite 和 React 創建登錄頁面! (第2部分)

  4. 使用此工作流程使您的 JavaScript 項目更安全

  5. 我應該使用 encodeURI 還是 encodeURIComponent 來編碼 URL?

  6. 我在使用原生 HTML、CSS 和 Javascript 製作遊戲時學到了什麼

  7. 在 mailto 上打開 Gmail:操作

  1. jquery ui 選擇菜單滾動條不起作用

  2. React、Vue 和 Svelte:比較選擇綁定

  3. JavaScript 對象鍵

  4. 在樣式組件中使用順風類

  5. 需要 React.js 開發者的幫助和建議!

  6. 停止請求加載 HTML 文件的腳本

  7. 什麼是 Node.js 和 Express.js

  1. 遊戲 CS 面試

  2. JavaScript 的異步性 - 承諾、回調和異步/等待

  3. 使用 Auth0 在 Angular 應用程序中進行用戶身份驗證

  4. 驗證 JavaScript 函數名稱