🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## js new的过程 1. 在内存中创建一个对象 2. 构造函数的 prototype 属性赋值给 新对象内部的 [[Prototype]] 3. 构造函数的 this 指向 新对象 4. 执行构造函数内部的代码,给新对象添加属性 5. 如果构造函数返回非空对象,则返回该对象,否则返回新对象 #### 用JS模拟new的过程 ~~~ function _new() { // 1、创建一个新对象 let target = {}; let [constructor, ...args] = [...arguments]; // 第一个参数是构造函数 // 2、原型链连接 target.__proto__ = constructor.prototype; // 3、将构造函数的属性和方法添加到这个新的空对象上。 let result = constructor.apply(target, args); if(result && (typeof result == "object" || typeof result == "function")){ // 如果构造函数返回的结果是一个对象,就返回这个对象 return result } // 如果构造函数返回的不是一个对象,就返回创建的新对象。 return target } let p2 = _new(Person, "小花") console.log(p2.name) // 小花 console.log(p2 instanceof Person) // true ~~~ ## 当普通函数使用 new 进行调用时,函数调用会变成构造函数调用