gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
js 用 prototype 添加多个方法
- User
js 用 prototype 添加多个方法
- Assistant
在 JavaScript 中,我们可以使用
prototype来为对象添加多个方法。下面是一个示例:// 定义一个构造函数 function Person(name, age) { this.name = name; this.age = age; } // 通过 prototype 添加方法 Person.prototype.sayHello = function() { console.log(`Hello, my name is ${this.name}.`); } Person.prototype.sayAge = function() { console.log(`I am ${this.age} years old.`); } // 创建一个实例对象 var person = new Person("John", 25); // 调用添加的方法 person.sayHello(); // 输出: Hello, my name is John. person.sayAge(); // 输出: I am 25 years old.在上面的例子中,我们定义了一个
Person构造函数,并通过prototype添加了sayHello和sayAge两个方法。然后,我们使用new关键字创建了一个person实例对象,并调用了添加的方法。最终,控制台会输出相应的信息。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.