不存在十全十美的文章,如同不存在彻头彻尾的绝望。------《且听风吟》
我们首先定义一个对象
|---------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 2 3 4 5 6 7 8 9 10 11
| hljs javascript 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())
|
打印结果为:
|-----------|------------------------------|
| 1
| hljs shell (ruben,21)
|
我们可以使用Person.prototype
去获取Person
的原型对象,从而更改类其中的方法
|-----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 2 3 4 5 6 7
| hljs javascript Person.prototype.toString = function(){ return "Person{" + "name='" + this.name + '\'' + ", age=" + this.age + '}'; } console.log(ruben.toString())
|
修改后结果为:
|-----------|------------------------------------------------|
| 1
| hljs shell Person{name='ruben', age=21}
|
打印一下原型对象呢
|-----------|------------------------------------------------------|
| 1
| hljs javascript console.log(Person.prototype)
|