手寫new 方法

function Person(){app

  this.name = name;this

  this.age = age;prototype

}io

  var p1 = new Person('珠峯',11)console

function myNew(...arg){function

  var obj = {};object

   var Constructor = arg.shift();方法

   obj.__proto__ = Constructor.prototype;call

   let res = Constructor.apply(obj,arg);//.call(obj,...arg)使用call的方法實現apply

   return typrOf res === 'object' ? res : obj;

}

var p2 = myNew(Person,'珠峯',11);

console.log(p1);

console.log(p2);//查看兩個打印是否同樣

相關文章
相關標籤/搜索