new关键字创建实例的原理
/*
1、new具体做了什么:创建一个给定构造函数的对象实例
2、具体过程
(1)创建一个空对象,假设名为obj,取值{}
(2)将obj的prototype属性指向构造函数constructor的prototype属性
(3)构造函数内部的this绑定到新建的对象obj上,由obj调用执行构造方法
(4)如果构造函数没有返回非原始值(也就是非引用类型的值)则返回该新建对象的obj,否则,返回引用类型的值
*/
function _new (construct,...args){
// const obj = {}
// var constructor = [].shift.call(arguments)
// obj.__proto__ = constructor.prototype
// 创建一个空对象obj,并将obj的prototype属性指向构造函数的原型对象
const obj = Object.create(construct.prototype)
//将construct上的this指向obj,调用construct
const result = construct.apply(obj,args)
// console.log(result); // undefined
// 如果result是对象,则返回这个result对象,如果不是(例如有些undefined、null类型的数据),则返回obj对象
return result instanceof Object ? result :obj
}
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayName = function(){
console.log(this.name);
}
const instance = _new(Person,"小明","23")
console.log(instance);
instance.sayName();