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

求助:为Contact对象实现print()方法以指定格式输出联系人数据

解决Contact Manager的print()方法问题

你的代码存在两个核心问题:

  1. 方法未关联到Contact实例:直接定义print=function(){...}只是创建了一个全局函数,没有挂载到Contact构造函数的原型或实例上,导致调用对象的print()时会提示方法不存在。
  2. 字符串拼接与属性引用错误:console.log("name:""" number")存在语法错误,既没有正确拼接字符串,也没有引用实例的name和number属性。

正确实现方式

方式一:挂载到构造函数原型(推荐)

这种方式让所有Contact实例共享同一个print方法,节省内存:

// 假设你的Contact构造函数结构如下
function Contact(name, number) {
  this.name = name;
  this.number = number;
}

// 给Contact原型添加print方法
Contact.prototype.print = function() {
  // 使用模板字符串拼接,清晰直观
  console.log(`name: ${this.name}, number: ${this.number}`);
};

// 测试代码
const contact1 = new Contact("张三", "13800138000");
const contact2 = new Contact("李四", "13900139000");
contact1.print(); // 输出 name: 张三, number: 13800138000
contact2.print(); // 输出 name: 李四, number: 13900139000

方式二:在构造函数内定义实例方法

每个实例会单独拥有一个print方法,适合需要为不同实例定制方法的场景:

function Contact(name, number) {
  this.name = name;
  this.number = number;

  this.print = function() {
    // 使用+号拼接字符串
    console.log("name: " + this.name + ", number: " + this.number);
  };
}

// 测试
const contact = new Contact("王五", "13700137000");
contact.print(); // 输出 name: 王五, number: 13700137000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:24:27