前言
此文通过重写的方式整理 new 的具体实现
new 原理
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例
new 使用
// 没有 return 语句
// 返回基于 Person.prototype 的新对象
function Person(age) {
this.age = age;
}
var person = new Person(18);
console.log(person); // Person {age: 18}
// return 对象
// 返回 return 后面的对象
function Person(age) {
this.age = age;
return { name: '手动返回一个对象' }
}
var person = new Person(18);
console.log(person); // {name: "手动返回一个对象"}
// return 基本数据类型
// 返回基于 Person.prototype 的新对象
function Person(age) {
this.age = age;
return 1
}
var person = new Person(18);
console.log(person); // Person {age: 18}
new 原理
- 创建一个空的简单 JavaScript 对象
- 链接这个对象到 new 后面的构造函数的对象原型
- 以新创建的对象会基础对象执行构造函数中的代码,类似 apply 的操作
- 如果该函数没有返回对象,则返回 this
new 模拟
function objectFactory(...params) {
// 创建基本对象
const newObj = {}
// 获取构造函数
const constructorFun = params.shift()
// obj 的隐式原型指向构造函数的原型
obj.__proto__ = constructorFun.prototype
// 基于新建的对象,执行构造函数
const result = constructorFun.apply(obj, params)
// 如果构造函数的返回结果是 object 类型 那么返回这个结果
if(typeof result === 'object'){
return result
}
// 否则返回新建的对象
return newObj
}