JavaScript代码输出undefined问题排查:Book类方法无返回值
问题排查与解决
问题根源
summary()和isAvailable()这两个方法内部仅编写了模板字符串表达式,但没有通过return语句返回结果。JavaScript中函数如果没有显式返回值,默认会返回undefined,这就是控制台输出undefined undefined的原因。
修复后的代码
function Book(title, author, isbn, stock, cost) { this.title = title; this.author = author; this.isbn = isbn; this.stock = stock; this.cost = cost; this.summary = function () { // 添加return返回模板字符串结果 return `${this.title} by ${this.author} (ISBN: ${this.isbn}) costs $${this.cost}`; }; this.isAvailable = function () { // 添加return返回三元表达式的结果 return this.stock > 0 ? `${this.title} is available` : `${this.title} is not available at the moment`; }; } const product = new Book( "The Design of Everyday Things", "Don Norman", "978 - 0 - 465 - 05571 - 5", 10, 17.99 ); console.log(product.summary()); console.log(product.isAvailable());
预期输出
"The Design of Everyday Things by Don Norman (ISBN: 978 - 0 - 465 - 05571 - 5) costs $17.99" "The Design of Everyday Things is available"
内容的提问来源于stack exchange,提问作者dheerajSan
相关产品推荐
相关产品推荐

