JavaScript定义商品类有属性:商品ID,商品名称name,商品价格price,商品数量num。有获取商品总价的方法getTPrice。并创建3种以上的商品,进行测试。代码怎么写
时间: 2024-06-03 08:07:50 浏览: 18
class Goods {
constructor(goodsId, name, price, num) {
this.goodsId = goodsId;
this.name = name;
this.price = price;
this.num = num;
}
getTPrice() {
return this.price * this.num;
}
}
let goods1 = new Goods(1, 'Apple', 2.5, 10);
let goods2 = new Goods(2, 'Banana', 1.5, 20);
let goods3 = new Goods(3, 'Orange', 3.0, 15);
console.log(goods1.getTPrice()); // 25
console.log(goods2.getTPrice()); // 30
console.log(goods3.getTPrice()); // 45
相关问题
JavaScript定义商品类有属性:商品ID,商品名称name,商品价格price,商品数量num。有获取商品总价的方法getTPrice。并创建3种以上的商品,进行测试。
// 定义商品类
class Product {
constructor(id, name, price, num) {
this.id = id;
this.name = name;
this.price = price;
this.num = num;
}
// 获取商品总价的方法
getTPrice() {
return this.price * this.num;
}
}
// 创建商品
const product1 = new Product(1, "苹果", 5, 10);
const product2 = new Product(2, "香蕉", 2, 20);
const product3 = new Product(3, "草莓", 10, 5);
// 测试获取商品总价的方法
console.log(product1.getTPrice()); // 50
console.log(product2.getTPrice()); // 40
console.log(product3.getTPrice()); // 50
要求:商品对象名称:goods 商品名称命名为:name 商品编号:num 商品毛重:weight 商品产地:address
好的,这是一个关于Java对象的问题。根据您的要求,可以定义一个商品对象,包含名称、编号、毛重和产地属性,代码如下:
```
public class Goods {
private String name;
private String num;
private double weight;
private String address;
public Goods(String name, String num, double weight, String address) {
this.name = name;
this.num = num;
this.weight = weight;
this.address = address;
}
// getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
```
在上述代码中,我们定义了一个Goods类,包含了名称、编号、毛重和产地属性,并提供了相应的构造方法和getter/setter方法。您可以根据需要对其进行修改和扩展。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)