为何我编写的Sandwich构造函数无法通过练习检测?
问题分析与解决方案
嘿,我一眼就发现你代码里的问题啦!你当前的构造函数把属性值硬编码成固定内容了,完全没用到传入的参数,这就是练习不通过的核心原因。
先看看你写的错误代码片段:
function Sandwich(bread, meat, vegetables){ this.bread = "Wheat"; this.meat = ["chicken", "hamb... }
问题点
你直接给this.bread赋值了固定字符串"Wheat",给this.meat赋值了固定数组,但构造函数明明接收了bread、meat、vegetables三个参数,却没有利用它们来动态设置实例的属性。这样不管你传入什么参数,创建出来的三明治实例属性都是固定的,肯定不符合练习要求。
正确的构造函数写法
把硬编码的值换成传入的参数就行:
function Sandwich(bread, meat, vegetables) { // 将传入的参数赋值给实例属性 this.bread = bread; this.meat = meat; this.vegetables = vegetables; }
使用示例
这样你就能根据不同参数创建不同的三明治实例了:
// 火鸡蔬菜三明治 const turkeySandwich = new Sandwich("Whole Grain", ["Turkey"], ["Lettuce", "Tomato"]); console.log(turkeySandwich.bread); // 输出 "Whole Grain" console.log(turkeySandwich.meat); // 输出 ["Turkey"] // 素食三明治 const veggieSandwich = new Sandwich("Sourdough", [], ["Spinach", "Avocado", "Cucumber"]); console.log(veggieSandwich.meat); // 输出 []
额外提示
如果需要给参数设置默认值(比如默认面包是Wheat,默认肉类为空数组),可以用ES6的默认参数语法优化:
function Sandwich(bread = "Wheat", meat = [], vegetables = []) { this.bread = bread; this.meat = meat; this.vegetables = vegetables; }
这样即使调用时不传某些参数,实例也会有合理的默认属性值。
内容的提问来源于stack exchange,提问作者user9753703
相关产品推荐
相关产品推荐

