
一、是什么
在JavaScript中,new操作符用于创建一个给定构造函数的实例对象
例子
1 2 3 4 5 6 7 8 9 10
| function Person(name, age){ this.name = name; this.age = age; } Person.prototype.sayName = function () { console.log(this.name) } const person1 = new Person('Tom', 20) console.log(person1) t.sayName()
|
从上面可以看到:
new 通过构造函数 Person 创建出来的实例可以访问到构造函数中的属性
new 通过构造函数 Person 创建出来的实例可以访问到构造函数原型链中的属性(即实例与构造函数通过原型链连接了起来)
现在在构建函数中显式加上返回值,并且这个返回值是一个原始类型
1 2 3 4 5 6
| function Test(name) { this.name = name return 1 } const t = new Test('xxx') console.log(t.name)
|
可以发现,构造函数中返回一个原始值,然而这个返回值并没有作用
下面在构造函数中返回一个对象
1 2 3 4 5 6 7 8
| function Test(name) { this.name = name console.log(this) return { age: 26 } } const t = new Test('xxx') console.log(t) console.log(t.name)
|
从上面可以发现,构造函数如果返回值为一个对象,那么这个返回值会被正常使用
二、流程
从上面介绍中,我们可以看到new关键字主要做了以下的工作:
举个例子:
1 2 3 4 5 6 7
| function Person(name, age){ this.name = name; this.age = age; } const person1 = new Person('Tom', 20) console.log(person1) t.sayName()
|
流程图如下:

三、手写new操作符
现在我们已经清楚地掌握了new的执行过程
那么我们就动手来实现一下new
1 2 3 4 5 6 7 8 9 10
| function mynew(Func, ...args) { const obj = {} obj.__proto__ = Func.prototype let result = Func.apply(obj, args) 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) p.say()
|
可以发现,代码虽然很短,但是能够模拟实现new