【发布时间】:2025-12-06 06:55:02
【问题描述】:
我正在尝试编写一个构造函数,该构造函数创建名为“customer”的客户对象,其中“customer”对象的每个实例都具有以下属性:
- 名称(字符串)
- 饮料(以字符串数组的形式),即 ["Coffee", "Cola"]
这是我的代码:
function customer(name, drink){
this.customername = name;
this.customerdrink = drink;
}
另一个名为“Order”的方法应该返回随机饮料(字符串格式):
function order(){
return.this.name + ": " + this.drink;
}
然后我将创建一个具有以下属性的“客户”对象实例:
- 姓名:“朱莉”
-
饮料:[“咖啡”、“可乐”]
var customer1 = { name: "Julie", drink: ["Coffee", "Cola"] }
然后我将调用“Order”方法以返回以下随机解决方案之一:
朱莉:“可乐”
朱莉:“咖啡”
如何让它随机返回饮料的类型?
编辑:
我应该这样写我的新客户实例吗?
var customer1 = {
name: "Julie",
drink: ["Coffee", "Cola"],
order: function(){
return.this.name + ": " + this.drink;
}
}
【问题讨论】:
标签: javascript object methods constructor properties