一、引
属实需要弄点原理的东西学习学习!
二、new 都干啥了
1.创建一个空对象
2.链接到原型
3.绑定this值
4.返回新对象
这四条,哪都能看到
那就一条条来写我们的 mynew
2.1 创建一个空对象
let obj = new Object();
let obj = {};
//喜欢怎么来就怎么来
2.2 链接到原型
let Constructor = [].shift.call(arguments);
//shift就是取第一个参数,然后this指向它,就是为了把构造函数赋值给 Constructor
obj.__proto__ = Constructor.prototype;
//然后让 obj 的 proto 属性指向构造函数的原型
2.3 绑定this
let result = Constructor.apply(obj,arguments);
//绑定this
2.4 返回obj
return typeof result === "object" ? result : obj;
//最后判断是 object 的话返回 object 不然直接返回对象 obj
三、试一下
function create(){
let obj = new Object();
let Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
let result = Constructor.apply(obj,arguments);
return typeof result === "object" ? result : obj;
}
function People(name,age){
this.name = name;
this.age = age;
}
let people1 = new People('nys',20);
console.log(people1.name); //nys
console.log(people1.age); //20
let people2 = create(People,'niyongsheng',18);
console.log(people2.name); //niyongsheng
console.log(people2.age); //18
成功!!!