首頁 > web前端 > js教程 > 主體

深入了解房產

Mary-Kate Olsen
發布: 2024-10-26 17:46:03
原創
449 人瀏覽過

Access to Properties-deep dive

JavaScript 是一種廣泛用於 Web 開發的多功能且強大的程式語言。它的關鍵特性之一是能夠定義對象,對象可以封裝屬性和方法。在與這些物件互動的各種方式中,存取器起著至關重要的作用。

讓我們更深入地了解如何存取 JavaScript 中的屬性。

使用 JavaScript 物件的胡蘿蔔蛋糕食譜

讓我們建立一個代表胡蘿蔔蛋糕食譜的 JavaScript 物件。我們將使用點符號和方括號符號來存取其屬性。

第 1 步:定義胡蘿蔔蛋糕對象

我們將定義一個對象,其中包含成分、烘焙時間和說明等屬性。

const carrotCake = {
    name: 'Carrot Cake',
    ingredients: {
        flour: '2 cups',
        sugar: '1 cup',
        carrots: '2 cups grated',
        eggs: '3 large',
        oil: '1 cup',
        bakingPowder: '2 tsp',
        cinnamon: '1 tsp',
        salt: '1/2 tsp'
    },
    bakingTime: '45 minutes',
    instructions: [
        'Preheat the oven to 350°F (175°C).',
        'In a bowl, mix flour, sugar, baking powder, cinnamon, and salt.',
        'In another bowl, whisk eggs and oil together.',
        'Combine the wet and dry ingredients, then fold in grated carrots.',
        'Pour the batter into a greased cake pan.',
        'Bake for 45 minutes or until a toothpick comes out clean.',
        'Let cool before serving.'
    ]
};

登入後複製
登入後複製

步驟 2:使用點表示法存取屬性

您可以使用點表示法存取胡蘿蔔蛋糕物件的屬性:

console.log(carrotCake.name); // Outputs: Carrot Cake
console.log(carrotCake.bakingTime); // Outputs: 45 minutes
console.log(carrotCake.ingredients.flour); // Outputs: 2 cups

登入後複製
登入後複製

步驟 3:使用括號表示法存取屬性

您也可以使用括號表示法,對於有空格的屬性或使用動態鍵時特別有用:

console.log(carrotCake['name']); // Outputs: Carrot Cake
console.log(carrotCake['bakingTime']); // Outputs: 45 minutes
console.log(carrotCake['ingredients']['sugar']); // Outputs: 1 cup
登入後複製
登入後複製

第 4 步:循環遍歷成分

您可以使用 for...in 迴圈遍歷成分以顯示所有成分:

for (const ingredient in carrotCake.ingredients) {
    console.log(`${ingredient}: ${carrotCake.ingredients[ingredient]}`);
}

登入後複製
登入後複製

這將輸出:

flour: 2 cups
sugar: 1 cup
carrots: 2 cups grated
eggs: 3 large
oil: 1 cup
bakingPowder: 2 tsp
cinnamon: 1 tsp
salt: 1/2 tsp

登入後複製

什麼是 JavaScript 物件存取器?

訪問器取得設定物件屬性值的方法。它們有兩種形式:getter 和 setter。

Getters:取得屬性值的方法。

Setters:設定屬性值的方法。

這些存取器提供了一種控制如何存取和修改屬性的方法。這對於資料驗證、封裝和提供計算屬性非常有用。

定義 Getter 和 Setter

在 JavaScript 中,您可以在物件字面量內或使用 Object.defineProperty 方法定義 getter 和 setter。

使用物件文字

以下是如何在物件字面量中定義 getter 和 setter 的範例:

let person = {
    firstName: "Irena",
    lastName: "Doe",
    get fullName() {
        return `${this.firstName} ${this.lastName}`; // Returns full name
    },
    set fullName(name) {
        let parts = name.split(' '); // Splits the name into parts
        this.firstName = parts[0]; // Sets first name
        this.lastName = parts[1]; // Sets last name
    }
};

console.log(person.fullName); // Outputs: Irena Doe
person.fullName = "Jane Smith"; // Updates first and last name
console.log(person.firstName); // Outputs: Jane
console.log(person.lastName); // Outputs: Smith
登入後複製

物件定義:您定義了一個名為 person 的對象,其屬性為firstName 和lastName。

  • Getter:fullName getter 連接firstName 和lastName 以在存取時傳回全名。
  • Setter:fullName setter 將提供的全名字串拆分為多個部分,並將第一部分指派給firstName,將第二部分指派給lastName。 用法: 當您記錄 person.fullName 時,它會正確輸出「Irena Doe」。 將 person.fullName 設為「Jane Smith」後,firstName 和 lastName 屬性會相應更新。

為了說明 getter/setter 和點/括號表示法之間的區別,讓我們增強一個胡蘿蔔蛋糕範例。我們將建立一個具有直接屬性存取和透過 getter 和 setter 進行屬性存取的物件。
步驟 1:定義胡蘿蔔蛋糕物件
我們將定義一個 carrotCake 對象,它使用直接屬性和特定屬性的 getter/setter。

const carrotCake = {
    name: 'Carrot Cake',
    ingredients: {
        flour: '2 cups',
        sugar: '1 cup',
        carrots: '2 cups grated',
        eggs: '3 large',
        oil: '1 cup',
        bakingPowder: '2 tsp',
        cinnamon: '1 tsp',
        salt: '1/2 tsp'
    },
    bakingTime: '45 minutes',
    instructions: [
        'Preheat the oven to 350°F (175°C).',
        'In a bowl, mix flour, sugar, baking powder, cinnamon, and salt.',
        'In another bowl, whisk eggs and oil together.',
        'Combine the wet and dry ingredients, then fold in grated carrots.',
        'Pour the batter into a greased cake pan.',
        'Bake for 45 minutes or until a toothpick comes out clean.',
        'Let cool before serving.'
    ]
};

登入後複製
登入後複製
  • 第 2 步:使用點和括號表示法存取屬性 讓我們使用點表示法直接存取和修改屬性:
console.log(carrotCake.name); // Outputs: Carrot Cake
console.log(carrotCake.bakingTime); // Outputs: 45 minutes
console.log(carrotCake.ingredients.flour); // Outputs: 2 cups

登入後複製
登入後複製
  • 第 3 步:使用 Getter 和 Setter 存取屬性 現在,讓我們使用 getter 和 setter 來存取和修改屬性:
console.log(carrotCake['name']); // Outputs: Carrot Cake
console.log(carrotCake['bakingTime']); // Outputs: 45 minutes
console.log(carrotCake['ingredients']['sugar']); // Outputs: 1 cup
登入後複製
登入後複製
  • 第4步:更新成分 使用方法更新成分:
for (const ingredient in carrotCake.ingredients) {
    console.log(`${ingredient}: ${carrotCake.ingredients[ingredient]}`);
}

登入後複製
登入後複製

讓我們回顧一下差異

點/括號表示法:

  • 直接存取或修改屬性。
  • 不應用任何驗證或邏輯。例如,carrotCake._name = ''; 將覆蓋名稱而不進行檢查。 ###取得器/設定器:
  • 提供存取和修改屬性的受控方式。
  • 可以包含自訂邏輯,例如設定器中的驗證。例如,carrotCake.name = '';防止設定空名稱。

此範例說明如何在 JavaScript 物件中使用這兩種方法,並強調了 getter 和 setter 在封裝邏輯和確保資料完整性方面的優勢。

使用訪問器的好處

  • 封裝
    存取器可讓您隱藏物件的內部表示,同時公開更清晰的介面。這是物件導向程式設計中封裝的基本原則。

  • 驗證
    Setter 可用於在更新屬性之前驗證資料。這可確保物件保持有效狀態。

概括

在此範例中,我們建立了一個簡單的 JavaScript 物件來表示胡蘿蔔蛋糕食譜。我們使用點和括號表示法存取其屬性,示範了 JavaScript 中屬性存取器的多功能性。

JavaScript 物件存取器是一項強大的功能,可以增強與物件屬性互動的方式。透過使用 getter 和 setter,您可以為物件新增封裝、驗證、計算屬性和唯讀屬性。理解和利用這些存取器可以產生更健壯、可維護和更簡潔的程式碼。當您繼續探索和掌握 JavaScript 時,將存取器合併到您的物件中無疑將成為您的程式設計工具包中的一個有價值的工具。

以上是深入了解房產的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!