js new所做的事

48 阅读1分钟
  1. 创建临时对象
  2. 绑定原型
  3. 指定this = 临时对象
  4. 执行构造函数
  5. 返回临时对象
function cat(name) {
  var tempObj={} //①创建临时对象
  tempObj.__proto__ = cat.prototype//②绑定原型
  tempObj.name = name
  return tempObj//③return临时对象
}

cat.prototype = {//④共有属性统一叫做prototype
  type:'animal',
  run: function () {
    console.log('running');
  }
}

使用new创建

function cat(name) {
  this.name = name
}
cat.prototype.type= "animal"
cat.prototype.run=function () {
    console.log("running");
  }
  
let cat1 = new cat('hal')
console.log(cat1);