You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中自定义book函数的info方法仅返回最后一个参数,原因何在?

问题原因及修复方案

这是因为你在return语句里用了JavaScript逗号运算符的特性:逗号运算符会从左到右依次计算每个表达式,但最终只会返回最后一个表达式的结果。所以return(title, author, pages, read)本质上和return read是一样的,自然只会输出最后一个参数。

几种修复方式:

  • 返回对象(推荐):能完整保留所有属性,方便后续操作
this.info = function() {
    return { title: this.title, author: this.author, pages: this.pages, read: this.read };
    // 或者用ES6简写:return { title, author, pages, read };
}

调用后会输出包含所有属性的对象:{ title: 'TheHobbit', author: 'J.R.R. Tolkien', pages: '295 pages', read: 'read' }

  • 返回拼接字符串:如果info方法是要返回可读的书籍描述
this.info = function() {
    return `${this.title} by ${this.author}, ${this.pages}, ${this.read}`;
}

输出结果:TheHobbit by J.R.R. Tolkien, 295 pages, read

  • 返回数组:需要按顺序的属性列表时使用
this.info = function() {
    return [this.title, this.author, this.pages, this.read];
}

输出结果:['TheHobbit', 'J.R.R. Tolkien', '295 pages', 'read']

另外补充一点:在实例方法里,建议用this.title这类实例属性,而不是直接引用构造函数的参数,虽然两种方式都能运行,但前者更清晰地表明是在访问实例的属性,代码可读性更高。

内容的提问来源于stack exchange,提问作者Duskope

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:01:06