class = (ES6 feature) provides a more structured and cleaner way to work with objects compared to traditional constructor function
- 它其实是基于 构造函数 + prototype 的封装,更简洁、可读性更好
- 用 class 可以把 属性(数据)和 方法(功能)封装在一个对象蓝图里。
class Product{
constructor(name, price){
this.name = name; // 普通属性
this.price = price; // 普通属性
}
displayProduct(){ // 方法(挂在原型 Product 上)
//方法不会在每个对象里复制一份,而是存在于类的 Product 上,所有对象共享。
console.log(this.name);
console.log(`price:$${this.price}`);
}
calculateTotal(){
return this.price + (this.price * tax);
}
}
const tax = 0.15 // 外部变量,全局税率
const product1 = new Product("shirt", 99);
const product2 = new Product("Pants", 89);
const product3 = new Product("Underwear", 59);
product1.displayProduct();
console.log(`price with tax: $${product2.calculateTotal()}`);output:
shirt
price:$99
price with tax: $102.35
=== Code Execution Successful ===