Appearance
new 操作符
new Foo() 做了哪些事情?
- 创建一个空对象
js
const obj = {};- 这个对象的隐式原型指向函数的显示原型 (即
obj.__proto__ === Foo.prototype)
js
obj.__proto__ = Foo.prototype;- this 指向这个空对象,并且执行构造函数
js
const result = Foo.apply(obj, args);- 返回这个创建的对象 (前提:没有显示的返回对象)
- 基本类型 / 无返回值,就返回创建的对象
- 如果返回值是 obj / fn,返回该值
js
if (
(typeof result === "object" && result !== null) ||
typeof result === "function"
)
return result;
return obj;用法
js
function Info(name, age) {
this.name = name;
this.age = age;
}
// {name: 'ice', age: 25}
const res = new Info("ice", 25);实现
js
function Info(name, age) {
this.name = name;
this.age = age;
}
function MyNew(Fn, ...args) {
// 1. 创建一个新对象
const obj = {};
// 2. obj.__proto__ = Fn.prototype
Object.setPrototypeOf(obj, Fn.prototype);
// 3. Fn 函数的 this,修改为 obj,并且执行代码
const result = Fn.apply(obj, args);
// 4. 如果是 object 类型,或者是 func 类型,返回 result
if (
(typeof result === "object" && result !== null) ||
typeof result === "function"
)
return result;
// 5. 否则,返回 result 对象
return obj;
}
// {name: 'ice', age: 25}
const res = MyNew(Info, "ice", 25);其中,第一步和第二步可以合并为:
js
const obj = Object.create(Fn.prototype);