자산 심층 분석에 대한 액세스
Oct 26, 2024 pm 05:46 PMJavaScript는 웹 개발에 광범위하게 사용되는 다재다능하고 강력한 프로그래밍 언어입니다. 주요 기능 중 하나는 속성과 메서드를 캡슐화할 수 있는 개체를 정의하는 기능입니다. 이러한 개체와 상호 작용하는 다양한 방법 중에서 접근자는 중요한 역할을 합니다.
자바스크립트에서 속성에 액세스하는 방법을 더 자세히 살펴보겠습니다.
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단계: 점 표기법을 사용하여 속성에 액세스
점 표기법을 사용하여 carrotCake 개체의 속성에 액세스할 수 있습니다.
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: 속성 값을 가져오는 메서드입니다.
Setter: 속성 값을 설정하는 메서드입니다.
이러한 접근자는 속성에 액세스하고 수정하는 방법을 제어하는 방법을 제공합니다. 이는 데이터 검증, 캡슐화 및 계산된 속성 제공에 유용할 수 있습니다.
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
객체 정의: firstName 및 lastName 속성을 사용하여 person이라는 객체를 정의했습니다.
- 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단계: 당근 케이크 개체 정의
직접 속성과 특정 속성에 대한 getter/setter를 모두 사용하는 carrotCake 객체를 정의하겠습니다.
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 = ''; 확인 없이 이름을 덮어씁니다. ###게터/세터:
- 속성에 액세스하고 수정하는 통제된 방법을 제공합니다.
- setter의 유효성 검사와 같은 사용자 정의 논리를 포함할 수 있습니다. 예: carrotCake.name = ''; 빈 이름을 설정하는 것을 방지합니다.
이 예에서는 JavaScript 개체에서 두 가지 접근 방식을 모두 사용할 수 있는 방법을 보여주고 논리를 캡슐화하고 데이터 무결성을 보장하기 위한 getter 및 setter의 이점을 강조합니다.
접근자 사용의 이점
캡슐화
접근자를 사용하면 더 깔끔한 인터페이스를 노출하면서 객체의 내부 표현을 숨길 수 있습니다. 이는 객체지향 프로그래밍에서 캡슐화의 기본 원칙입니다.검증
Setter는 속성을 업데이트하기 전에 데이터의 유효성을 검사하는 데 사용할 수 있습니다. 이렇게 하면 객체가 유효한 상태로 유지됩니다.
요약
이 예에서는 당근 케이크 레시피를 나타내는 간단한 JavaScript 개체를 만들었습니다. 점과 대괄호 표기법을 모두 사용하여 속성에 액세스하여 JavaScript에서 속성 접근자가 얼마나 다양한지 보여줍니다.
JavaScript 객체 접근자는 객체 속성과 상호 작용하는 방식을 향상시키는 강력한 기능입니다. getter 및 setter를 사용하면 캡슐화, 유효성 검사, 계산된 속성 및 읽기 전용 속성을 개체에 추가할 수 있습니다. 이러한 접근자를 이해하고 활용하면 더욱 강력하고 유지 관리가 가능하며 깔끔한 코드를 만들 수 있습니다. 계속해서 JavaScript를 탐색하고 익히면서 접근자를 개체에 통합하는 것은 의심할 여지 없이 프로그래밍 툴킷에서 귀중한 도구가 될 것입니다.
위 내용은 자산 심층 분석에 대한 액세스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

인기 기사

인기 기사

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









