求助:为Contact对象实现print()方法以指定格式输出联系人数据
解决Contact Manager的print()方法问题
你的代码存在两个核心问题:
- 方法未关联到Contact实例:直接定义
print=function(){...}只是创建了一个全局函数,没有挂载到Contact构造函数的原型或实例上,导致调用对象的print()时会提示方法不存在。 - 字符串拼接与属性引用错误:
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
相关产品推荐
相关产品推荐

