New内部原理:
- 产生一个空对象,对象的隐式原型__proto__属性指向该类(构造函数)的prototype属性,并将该对象赋值给this
- 给this赋值
- 返回这个this对象(注: 当构造函数内部设置返回且返回值为基本数据类型的时候,则忽略,依旧返回该this,否则,以自定义返回为准)
function Say(name) {
this.name = name;
}
Say.prototype.back = function () {
console.log('back');
}
Say.prototype.something = function () {
console.log('something', this.name);
}
let newSay = new Say('haha');
// newSay.back();
// newSay.something();
// new内部
function _new(fn, ...params){
// let obj = {};
// obj.__proto = fn.prototype;
let obj = Object.create(fn.prototype);
res = fn.apply(obj, params);
if (res !== null &&( typeof res === 'object' || typeof res === 'function' )) {
return res;
} else {
return obj;
}
}
let new1 = _new(Say, 'test');
new1.back(); // back
new1.something(); // something test