概述:
JavaScript 中只有对象。
面向类的语言:类可以被
复制(或者说实例化)多次,就像用模具制作东西一样。实例化(或者继承)一个类意味着“把类的行为复制到物理对象中”,对于每一个新实例来说都会重复这个过程。
Js:没有类似的复制机制。
不能创建一个类的多个实例,只能创建多个对象。它们[[
Prototype]]
关联的是同一个对象。
这些对象之间并不会完全失去联系,它们是互相关联的。
例如:
class Person {
constructor(props) {
this.canRun = true;
this.canWalk = true;
this.canFly = true;
this.firstName = null;
}
setFirstName(val) {
this.firstName = val;
return this;
}
getFirstName() {
return this.firstName;
}
}
export default Person;
const A = new Person(); // 关联两个对象最常用的方法是使用 new 关键词进行函数调用
// eslint-disable-next-line no-proto
A.__proto__.getFirstName = function ss() {
return `${this.firstName}-suffix`;
};
const B = new Person();
console.log(B.setFirstName('B').getFirstName());
console.log(Person.prototype.getFirstName);
通过 new 创建了 A 和 Person 的关联,有意的替换掉 Person 中的 getFirstName 方法,会导致Person被更改,通过 new 创建的其他对象,比如B也会被更改。