awesome-interview icon indicating copy to clipboard operation
awesome-interview copied to clipboard

New 操作符的原理 | HZFE - 剑指前端 Offer

Open utterances-bot opened this issue 5 years ago • 5 comments

New 操作符的原理 | HZFE - 剑指前端 Offer

相关问题

https://febook.hzfe.org/awesome-interview/book2/js-new

utterances-bot avatar Oct 27 '21 05:10 utterances-bot

function fakeNew() {

函数签名的入参漏了吧

babopo avatar Oct 27 '21 05:10 babopo

function fakeNew() {

函数签名的入参漏了吧

没有漏 可以正常运行的

xiaokk06 avatar Oct 31 '21 08:10 xiaokk06

function fakeNew() { 函数签名的入参漏了吧

没有漏 可以正常运行的

抱歉看错了,close吧

babopo avatar Oct 31 '21 10:10 babopo

这里漏了类型为 function 的情况

// 返回新对象
return typeof ret === "object" && ret !== null ? ret : obj;

应该是

// 返回新对象
return (typeof ret === "object" && ret !== null) || typeof ret === 'function' ? ret : obj;

MinimalistYing avatar Jul 26 '22 14:07 MinimalistYing

function myNew(Constructor, ...args) { // 1. 创建一个新对象,并将其原型指向构造函数的prototype const obj = Object.create(Constructor.prototype);

// 2. 执行构造函数,并将this指向新对象 const result = Constructor.apply(obj, args);

// 3. 如果构造函数返回了一个对象,则返回该对象;否则返回新创建的对象 return result instanceof Object ? result : obj; }

kl404 avatar Feb 11 '25 09:02 kl404