Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

js 用 prototype 添加多个方法

  1. User

    js 用 prototype 添加多个方法

  2. 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 实例对象,并调用了添加的方法。最终,控制台会输出相应的信息。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.