用funciton当构造函数时

用function 时 ,为什么把方法挂在原型上面。

将属性和方法都写在构造函数中没问题,但问题在于每次进行实例化的过程中,重复创建功能不变的方法。

由于方法本质上是函数,其实也就是在堆内存中又新建了一个对象空间存储函数,造成了不必要的资源浪费。

function Dep(name) {
  this.name = name;
  this.subs = [];
}

Dep.prototype = {
  addSub(){
    console.log(this.name)
  },
  notify() {
    console.log(notify)
  }
}

 

相当于 class

class Dep {
  constructor(name) {
    this.name = name
  }
  addSub(){
    console.log(this.name)
  }
  showInfo() {
    console.log(this.name)
  }
}

 

posted on 2021-01-18 15:35  京鸿一瞥  阅读(431)  评论(0)    收藏  举报