<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>new一个对象的过程</title>
</head>
<body>
<script>
function newObj(constructor, ...args) {
if (typeof constructor !== 'function') throw new Error('第一个参数需是构造函数')
// setp1: 创建一个空对象o
const o = {}
// setp2:将o作为this参数调用构造函数constructor,并接收返回值result
const result = constructor.apply(o, args)
// setp3:设置原型链
o.__proto__ = constructor.prototype
// setp4:判断返回值result是否为对象类型,是的话返回result,不是的话返回对象o
if (typeof result === 'object') return result
else return o
}
function Person(name, age) {
this.name = name
this.age = age
}
const p1 = new Person('张三', 20)
console.log('p1', p1)
const p2 = newObj(Person, '李四', 30)
console.log('p2', p2)
</script>
</body>
</html>

**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。