先看看构造函数new之后对象的样子
我们可以看到对象中有三个属性:a、b、__ proto__,现在用代码去模拟new方法。
function Test(a, b){
this.a = a;
this.b = b;
}
Test.prototype.add = function(){}
function myNew(){
//获取第一个参数
var constructor = [].shift.call(arguments),
_this = {};
//给_this添加__proto__属性
_this.__proto__ = constructor.prototype;
//执行Test函数, arguments = [3, 4]
constructor.apply(_this, arguments);
return _this;
}
var test1 = myNew(Test, 3, 4);
console.log(test1);
结果: