new手写实现过程

new命令的基本用法

new命令的作用,就是执行构造函数,返回一个实例对象。

1
2
3
4
5
6
var Vehicle = function () {
this.price = 1000;
};

var v = new Vehicle();
v.price // 1000

new命令的原理

  1. 创建一个空对象,作为将要返回的对象实例。
  2. 将这个空对象的原型,指向构造函数的prototype属性。
  3. 将这个空对象赋值给函数内部的this关键字。
  4. 开始执行构造函数内部的代码。

手写new命令过程

1
2
3
4
5
6
7
8
9
10
function mynew(Func, ...args) {
// 1.创建一个新对象
const obj = {}
// 2.新对象原型指向构造函数原型对象
obj.__proto__ = Func.prototype
// 3.将构建函数的this指向新对象
let result = Func.apply(obj, args)
// 4.根据返回值判断,如果对象没有返回值,result会为undefine
return result instanceof Object ? result : obj
}

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function mynew(func, ...args) {
const obj = {}
obj.__proto__ = func.prototype
let result = func.apply(obj, args)
return result instanceof Object ? result : obj
}
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.say = function () {
console.log(this.name)
}

let p = mynew(Person, "huihui", 123)
console.log(p) // Person {name: "huihui", age: 123}
p.say() // huihui

new手写实现过程
https://tian-1-2.github.io/typblog/2022/05/23/2022523-new手写实现过程/
作者
田云鹏
发布于
2022年5月23日
许可协议