ES6 class 理解

/** 传统构造函数 */
(function() {
  // 1. 设置一个构造函数
  function Animal(type, name) {
    this.type = type;
    this.name = name;
  }

  // 2. 在 Animal 构造函数的原型对象上 添加一个 getAnimalName 的方法
  Animal.prototype.getAnimalName = function() {
    return this.name
  }

  // 3. new 出 cat dog 这样的实例;可以发现, 每个实例上均有 getAnimalName 方法;
  const cat = new Animal('cat', '小花');
  // console.log(cat.getAnimalName())
  const dog = new Animal('dog', '大黄');
  // console.log(dog.getAnimalName())

  // 4. cat 实例上虽然没有 constructor 属性,但是 cat.__proto__ 上有 constructor 属性,且指向 Animal; 根据原型链的查找规则,实例没有的方法,会沿着 __proto__ 查询;
    // console.log(cat.constructor === Animal) // true
})();



/** ES6 class: 不存在变量提升 */

(function() {
  class Animal {
    // 这里的 constructor === function Animal(type, name) {}; 也就是说 constructor 方法内部的逻辑,就是构造函数内部的代码逻辑
    constructor(type, name) {
      this.type = type
      this.name = name
    }

    /**
     *  在 class 内部直接定义的方法;也就是 写在 原型对象 prototype 中的
     *  Animal.prototype = { getAnimalName, getAnimalType }
     */
    getAnimalName() {
      return this.name
    }
    getAnimalType() {
      return this.type
    }

    /**
     * 静态方式:直接定义在 Animal 上面的方式,只能通过 Animal.propName 的方法调用,实例上不可调用
     * 通过关键字  static 来实现
     */

    static classmethod() {
      return 'class'
    }

    // 资料上说这种方式也不生效的,但是测试发现,有效果
    static env1 = 'env1'

    // 这种方法设置的不是静态属性,而是动态属性,也就是说是设置在 prototype 上的,实例可以调用
    env2 = 'env2'
  }

  /**
   * 静态方式: 目前只能通过下面这种方法;
   */ 
  Animal.environment = 'forest'

  const dog = new Animal('dog', '大黄');
  
  // console.log(Animal.classmethod()) // class
  // console.log(Animal.env1) // env1
  // console.log(Animal.env2) // undefined
  // console.log(Animal.environment) // forest

  // console.log(dog.classmethod()) // dog.classmethod is not a function
  console.log(dog.env1) // undefined
  console.log(dog.env2) // env2
  console.log(dog.environment) // undefined
  console.log(dog.getAnimalName()) // 大黄
})(); 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值