Menu
CoddyTech

클래스와 생성

Coddy의 C++ 개발자를 위한 JavaScript 코스 레슨. 48개 중 32번째.

C++ 클래스 값은 직접 저장하고 특수 멤버 함수에 따라 복사할 수 있습니다. JavaScript 클래스는 new를 사용해 생성하며, 메서드가 프로토타입에 있는 참조 객체를 만듭니다. 수신 객체는 this이지만, 대입은 복사 생성자를 호출하는 대신 동일성을 공유합니다. 값 중심 모델을 변환할 때는 필드의 소유 관계를 명확히 하세요.

C++

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <optional>
#include <functional>
#include <sstream>
#include <variant>
#include <memory>
#include <cctype>
#include <stdexcept>

struct Item {std::string name;};
int main() {
std::cout << std::boolalpha;
Item item{"pen"};std::cout << item.name << "\n";
}

JavaScript

class Item { constructor(name) { this.name=name; } }
console.log(new Item("pen").name);

이식 시 주의할 점: JavaScript 클래스 인스턴스는 new로 생성하세요.

이 과제에도 새로운 입력에 동일한 규칙이 적용됩니다. 제공된 solve 함수에서 값을 반환하고, 입력 및 출력 처리는 driver.js에 그대로 두세요.

challenge icon

챌린지

쉬움

입력은 {name,quantity}입니다. Item.js에 해당 인스턴스 필드를 가진 Item을 정의하세요. exercise.js에서 [item.name,item.quantity]를 반환하세요.

입력은 JSON 값 하나입니다. 잠금이 해제된 파일을 수정하되, exercise.js부터 시작하세요. 잠긴 상태로 표시된 driver.js는 solve(input)을 호출하고, 반환값을 압축된 JSON 형식으로 출력한 뒤 줄바꿈을 하나 추가합니다. 진단용 출력을 추가하지 마세요. 테스트는 전체 출력을 비교합니다. 모든 숫자 입력과 계산된 정수 합계는 안전한 정수 범위 내에 있습니다.

입력 예시:

{"name":"pen","quantity":2}

예상 출력:

["pen",2]

잠긴 드라이버는 solve를 호출하기 전에 새 인스턴스로 내보낸 클래스 API도 직접 확인합니다. 이름이 지정된 클래스와 문서에 명시된 필드 및 메서드를 구현하세요. 최종 출력만 똑같이 만드는 것으로는 충분하지 않습니다. driver.js의 모든 고정 검사를 확인할 수 있습니다.

직접 해보기

import assert from "node:assert/strict";
// 고정된 API 검사: 클래스 모듈은 과제 명세의 일부입니다.
import { Item } from "./Item.js";
const first = new Item("pen",2), second = new Item("",0);
assert.deepEqual([first.name,first.quantity,second.name,second.quantity],["pen",2,"",0]);
first.quantity=7;
assert.equal(second.quantity,0);
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin으로 하나의 JSON 값이 들어옵니다. 데이터를 반환하고, solve 내부에서는 출력하지 마세요.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 JavaScript의 모든 레슨

직접 연습해 보세요: 온라인 JavaScript 컴파일러