class 类和构造函数的区别, 以及与面向对象的关联

78 阅读1分钟
// "use strict";
class Father {
    #account = 0 // 私有属性 只能在类的内部使用
    constructor(name){ // constructor 是构造函数
      this.name = name
      this.printName = this.printName.bind(this) // 改变了this的指向, 此时this 便是 实例
    }
    static getStatic(){ // 静态方法 不可以被实例继承,而是直接通过类来调用
      console.log(1)
    }
    printName(name = 'there') {
      this.print(`Hello ${name}`);
    }
    print(text) {
      console.log(text);
    }
  }

  const father = new Father('伟杰')

  console.log(father.__proto__ === Father.prototype) // true  实例的__proto__ 指向构造函数的原型对象
  console.log(father.constructor === Father) // 实例的构造函数 就是 Class 类本身 同时也是 类的原型队象的构造函数 constructor
  console.log(Father.prototype.constructor === Father)

  class Children extends  Father{
    constructor(...arg){ // 子类中当没有定义 constructor 时, constructor 和 super会自动添加
        super(...arg) // 调用父类的constructor(x, y)
    }
  }

  const children = new Children('沐晨')

  console.log(children instanceof Children) // true
  console.log(children instanceof Father) // true