在实现new操作符之前,我们需要知道new都干了些什么
比如
var fn=function(){};
var fnObj=new fn();
1.创建了一个新对象
var obj=new Object()
2.设置原型链
obj.__proto__=constructor.prototype
//这里的constructor就是fn
3.让constructor的this指向obj,并执行constructor的函数体
var result=constructor.call(obj)
4.判断返回值类型,如果是值类型就返回obj,如果是引用类型就返回这个引用类型的对象
if(typeof(result)=="object")
{
fnObj=result;
}
else
{
fnObj=obj;
}
接下来就手写new
function myNew()
{
let obj={};
//绑定原型
obj.__proto__=Constructor.prototype;
let res=Constructor.apply(obj,arguments);
return typeof res === 'object' ? res : obj;
]
博客围绕new操作符展开,先介绍了new操作符的功能,包括创建新对象、设置原型链、让构造函数的this指向新对象并执行函数体,以及根据返回值类型决定最终返回对象。随后表示要手写实现new操作符。
166

被折叠的 条评论
为什么被折叠?



