Menu
CoddyTech

电商产品系统

本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 54 课,共 56 课。

challenge icon

挑战

这是一个在线商店的商品系统。商品有价格,实体商品(如笔记本电脑)会根据重量计算运费。数字商品(如电子书)则免运费。

你的任务是补全商品系统中缺失的方法:

1:补全 Product 类,位于 product.js 中:

  • 添加方法 getPrice(),返回 this.#price
  • 添加方法 getDescription(),返回 ${this.name} - $${this.#price}

2:补全 PhysicalProduct 类,位于 physicalProduct.js 中:

  • 添加方法 calculateShipping(),该方法:
    • 计算 this.weight * 0.5(每磅 50 美分)
    • 返回运费

亲手试试

import { Product } from './product.js';
import { PhysicalProduct } from './physicalProduct.js';

const book = new Product('Book', 20);
const laptop = new PhysicalProduct('Laptop', 1000, 5);

console.log(book.getDescription()); // 应显示:“Book - $20”
console.log(laptop.getDescription()); // 应显示:“Laptop - $1000  (5 lbs)”

console.log(`Shipping cost for laptop: $${laptop.calculateShipping()}`); // 应显示:“Shipping cost for laptop: $2.5”

console.log(`Book price: $${book.getPrice()}`); // 应显示:“20”
console.log(`Laptop price: $${laptop.getPrice()}`); // 应显示:“1000”

面向对象编程中的所有课

自己练习: JavaScript 在线编译器