外观
new 具体做了什么?
new 创建一个新对象,把这个对象的原型指到构造函数的 prototype,用它当 this 执行构造函数。如果构造函数返回的是对象,就用返回值;否则用刚创建的那个对象。
原理
js
function myNew(Constructor, ...args) {
const obj = Object.create(Constructor.prototype)
const result = Constructor.apply(obj, args)
return result !== null && typeof result === "object" ? result : obj
}返回函数也算对象,所以构造函数 return function(){} 时,new 的结果是这个函数,不是 obj。返回数字、字符串这些原始值会被忽略。
构造函数如果忘了 new,严格模式下 this 是 undefined,属性写不上去。类构造函数必须用 new,语言会直接抛错。
追问
和 Object.create 的差别?
Object.create(proto) 只设置原型,不执行构造函数。new 两件事都做。继承方法时用 Object.create,创建业务实例时用 new 或类。
箭头函数为什么不能 new?
没有 [[Construct]],也没有自己的 prototype 和 this。
易错点
- 构造函数返回
null时,结果仍是新对象。判断返回值要排除null。 myNew如果写成Constructor()而不apply到新对象,实例属性会丢。- 类的静态方法不会出现在实例上,
new不负责复制它们。