new操作符做了哪些事情
- 创建一个空的对象
- 链接到原型
- 绑定this执行,执行构造函数
- 确保返回的是对象
function newFactory (constructor) {
// 1: 创建新的对象
// 2: 链接原型
let obj = Object.create(constructor.prototype);
let args = Array.from(arguments).slice(1);
// 3: 绑定this
let result = constructor.apply(obj, args);
// 4: 返回该对象
return result instanceof Object ? result : obj;
}
function Cat (name, color) {
this.name = name;
this.color = color;
// return {
// name: 'zs'
// }
}
Cat.prototype.miao = function () {
console.log('喵~',);
}
let cat = newFactory(Cat, '大毛', '橘色')
在new的时候,会对构造函数的返回值做一些判断:
- 如果返回值是基础数据类型,则忽略返回值;
- 如果返回值是引用数据类型,则使用return 的返回,也就是new操作符无效;
网上的资料深浅不一,本人也是处在学习的过程中的总结,如果发现错误,欢迎留言指出~
**扫码加入前端群,分享技术难题~
**