zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js原型对象

JS对象 原型
2023-06-13 09:11:17 时间

我们首先定义一个对象

class Person {
  constructor(name,age) {
    this.name = name;
    this.age = age;
  }
  toString() {
    return '(' + this.name + ', ' + this.age + ')';
  }
};
let ruben = new Person("ruben",21);
console.log(ruben.toString())

打印结果为:

(ruben,21)

我们可以使用Person.prototype去获取Person的原型对象,从而更改类其中的方法

Person.prototype.toString = function(){
    return "Person{" +
            "name='" + this.name + '\'' +
            ", age=" + this.age +
            '}';
}
console.log(ruben.toString())

修改后结果为:

Person{name='ruben', age=21}

打印一下原型对象呢

console.log(Person.prototype)