Js之分析模仿类

概述: 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也会被更改。 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值