JavaScript构造函数返回多属性时仅输出最后一个值是什么原因?
问题原因
你的代码中return (title, author, pages, read)使用了JavaScript的逗号运算符,该运算符的规则是依次计算括号内的所有表达式,最终仅返回最后一个表达式的结果,所以你最终只会拿到最后一个参数read的值"nope"。
另外建议你在构造函数的方法内通过this访问实例属性,而非直接读取构造函数的参数:如果后续你修改了实例的属性值,构造函数的入参值是不会同步更新的,用this才能获取到实例的最新属性。
修复方案
根据你想要的返回格式选择对应写法即可:
- 若要返回包含所有属性的数组:将返回语句的括号替换为数组方括号
调用return [this.title, this.author, this.pages, this.read]console.log输出结果为:['lord of the rings', 'JRR', '366', 'nope'] - 若要返回你预期的逗号分隔字符串:使用模板字符串拼接属性
调用return `${this.title}, ${this.author}, ${this.pages}, ${this.read}`console.log输出结果为:lord of the rings, JRR, 366, nope - 若要返回包含所有属性的对象:写成对象字面量格式
return { title: this.title, author: this.author, pages: this.pages, read: this.read }
完整修正示例
function Book(title, author, pages, read) { this.title = title this.author = author this.pages = pages this.read = read this.bookInfo = function() { // 此处可根据需求替换为上面的任意返回写法 return [this.title, this.author, this.pages, this.read] } } const LOTR = new Book('lord of the rings', 'JRR', '366', 'nope'); console.log(LOTR.bookInfo());
内容的提问来源于stack exchange,提问作者nc14
相关产品推荐
相关产品推荐

