Daily-Question
Daily-Question copied to clipboard
【Q338】js 中在 new 的时候发生了什么
- 创建了一个新对象
- 链接到原型
- 绑定this指向 4.返回这个对象
function _new() {
let obj = {}
let Con = [].shift.call(arguments)
obj.__proto__ = Con.prototype
let result = Con.apply(obj, arguments)
return typeof obj === 'object' ? obj : {}
}
- 创建一个新的对象
- this 指向实例,并且执行函数
- 如果没有显式返回,则默认返回这个实例
- 创建了一个新对象
- 链接到原型
- 绑定this指向 4.返回这个对象
function _new() { let obj = {} let Con = [].shift.call(arguments) obj.__proto__ = Con.prototype let result = Con.apply(obj, arguments) return typeof obj === 'object' ? obj : {} }
如果构造器返回null 就不对了 因为 typeof null === 'object'
所以应该用 obj instanceof Object
- 创建了一个新对象
- 链接到原型
- 绑定这个指向 4.返回这个对象
function _new() { let obj = {} let Con = [].shift.call(arguments) obj.__proto__ = Con.prototype let result = Con.apply(obj, arguments) return typeof obj === 'object' ? obj : {} }
这个result没用啊
- 关联原型
- 调用函数,绑定参数
- 返回执行,特别需要处理
null
、object
场景
function myNew(...rest) {
const fn = [].slice.call(rest, 0, 1)[0];
const params = [].slice.call(rest, 1);
const ret = Object.create(fn.prototype);
const result = fn.apply(ret, params);
return typeof result === 'object' ? result || ret : ret ;
}
function myNew(fn, ...args) {
const instance = Object.create(fn.prototype);
const ret = fn.apply(instance, args);
return typeof ret === "object" && ret !== null ? ret : instance;
}