협력 객체와 위임
Coddy의 C 개발자를 위한 JavaScript 코스 레슨. 48개 중 38번째.
C에서는 함수 포인터와 선택적 컨텍스트를 통해 동작을 주입할 수 있습니다. JavaScript에서는 인터페이스를 선언하지 않고도 필요한 메서드가 있는 객체를 저장할 수 있습니다. 대입은 해당 객체를 공유하며 복사하지 않습니다. 호출자의 협력 객체를 유지하고 메서드 계약을 문서화하세요. 일반 JavaScript 컴파일러는 런타임 호출 경계를 확인하지 않기 때문입니다.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>
static int fee_amount(void){return 4;}struct Checkout {int (*fee)(void);};static int checkout_total(const struct Checkout *c,int n){return n+c->fee();}
int main(void) {
struct Checkout checkout={fee_amount};printf("%d\n",checkout_total(&checkout,6));
return 0;
}
JavaScript
class Fee { amount() { return 4; } }
class Checkout { constructor(fee) { this.fee=fee; } total(n) { return n+this.fee.amount(); } }
console.log(new Checkout(new Fee()).total(6));편집 가능한 모듈에서 과제를 구현하세요. 화면에 표시된 driver.js 검사를 확인하고 문서화된 내보내기 API를 유지하세요.
챌린지
쉬움입력은 [subtotal,fee]입니다. Fee 객체를 만들고 Checkout에 주입하세요. checkout.total(subtotal)을 반환하세요. 두 값은 모두 음이 아닌 정수입니다.
입력은 JSON 값 하나입니다. exercise.js부터 시작해 잠금 해제된 파일을 수정하세요. 잠겨 있지만 볼 수 있는 driver.js는 solve(input)을 호출하고 반환값을 압축된 JSON으로 출력한 뒤 줄바꿈을 하나 추가합니다. 진단용 출력을 추가하지 마세요. 테스트는 전체 출력을 비교합니다. 모든 숫자 입력과 계산된 정수 합계는 안전한 정수 범위 내에 있습니다.
입력 예시:
[6,4]예상 출력:
10잠긴 드라이버는 solve를 호출하기 전에 새 인스턴스를 만들어 내보낸 클래스 API도 직접 확인합니다. 이름이 지정된 클래스와 문서화된 필드 및 메서드를 구현하세요. 최종 출력만 재현하는 것으로는 충분하지 않습니다. driver.js의 모든 고정 검사를 확인할 수 있습니다.
Checkout은 주입된 객체를 유지하고, 다른 객체가 해당 메서드를 구현한 경우를 포함해 합계를 계산할 때마다 그 객체의 amount() 메서드를 호출해야 합니다.
직접 해보기
import assert from "node:assert/strict";
// 고정된 API 검사: 클래스 모듈은 과제 명세의 일부입니다.
import { Fee } from "./Fee.js";
import { Checkout } from "./Checkout.js";
const fee=new Fee(4), checkout=new Checkout(fee);
assert.equal(fee.amount(),4); assert.equal(checkout.total(6),10);
assert.equal(new Checkout(new Fee(0)).total(5),5);
const changing={amount() { return 7; }};
const other=new Checkout(changing);
assert.equal(other.total(2),9);
changing.amount=()=>1;
assert.equal(other.total(2),3);
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)));
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 JavaScript의 모든 레슨
직접 연습해 보세요: 온라인 JavaScript 컴파일러