我坚持这个关于构造函数的练习:
声明一个带有三个参数的Sandwich
构造函数:
1. bread
(字符串) - 三明治的面包类型(例如" Wheat")
2. meat
(数组) - 放在三明治上的肉类
(例如[]
吃素食三明治!)
3. vegetables
(数组) - 包含在三明治中的蔬菜
我尝试使用此代码,但它没有通过练习:
function Sandwich(bread, meat, vegetables){
this.bread = "Wheat";
this.meat = ["chicken", "hamburger"];
this.vegetables = ["tomatoes", "potatoes", "onions"];
}
new Sandwich();
答案 0 :(得分:1)
function Sandwich(bread, meat, vegetables){
this.bread = bread;
this.meat = meat;
this.vegetables = vegetables;
}
const meatSandwich = new Sandwich("Wheat", ["chicken", "hamburger"], ["tomatoes", "potatoes", "onions"]);
答案 1 :(得分:0)
我猜你完全错过了这个主意。您应该将通过构造函数传递的值分配给对象。
function Sandwich(bread, meat, vegetables){
this.bread = bread;
this.meat = meat;
this.vegetables = vegetables;
}
var mySandwich = new Sandwich("Wheat", ["chicken", "hamburger"], ["tomatoes", "potatoes", "onions"]);
现在执行您想要对mySandwich
对象执行的操作。
答案 2 :(得分:-2)
在构造函数上使用参数的想法是设置相应的属性。未设置硬编码值。尝试:
function Sandwich(bread, meat, vegetables){
this.bread = bread;
this.meat =meat;
this.vegetables =vegetables;
}