要想实现new的功能,我们首先要知道new是干什么的呢?
在js中 var a = new A() 后
1.创建一个空对象obj{}
2.将a的this指向obj{}
3.将a的_proto_指向A的prototype
4.执行A的构造函数
5.返回obj
代码级实现:
function Test (name) {
this.name = name;
this.test = '????';
}
Test.prototype.test2 = function () {
console.log('测试原型链上的方法!');
}
function _new () {
let newObj = {};
let Constructor = Array.prototype.shift.call(arguments);
newObj.__proto__ = Constructor.prototype;
Constructor.apply(newObj,arguments);
return newObj;
}
var t = _new(Test,'yz');
t.test2();