You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
由于 new 是保留字,我们没有办法直接覆盖,所以我们创建一个函数 _new,来模拟 new 的实现,调用时,new Foo(args) 等同于 _new(Foo, args):
function_new(){letconstructor=[].shift.call(arguments);letcontext=Object.create(constructor.prototype);letresult=constructor.apply(context,arguments);return(typeofresult==='object'&&typeofresult!==null) ? result : context;}
new 的实现原理是什么?
什么是 new
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。MDN
有点晦涩难懂,简单来说就是:
实现原理
使用 new 命令时,它后面的构造函数会执行以下操作:
JavaScript
对象prototype
属性this
绑定到空对象this
,即新创建的对象步骤 3 中,将新创建的对象作为了当前函数
this
的上下文,这也是为什么通过new
创建实例时,构造函数内部的this
指向创建的实例对象的原因。Tips: 构造函数之所以叫 “构造函数”,可能也是因为这个函数的目的,就是操作一个空对象(
this
),然后将它 “构造” 成我们想要的样子吧。 -- 阮一峰模拟实现一个 new
由于
new
是保留字,我们没有办法直接覆盖,所以我们创建一个函数_new
,来模拟new
的实现,调用时,new Foo(args)
等同于_new(Foo, args)
:上面的实现中,
prototype
属性,相当于将空对象的原型指向构造函数的原型:context
,即当前的this
判断返回值的类型是有必要的,因为如果构造函数返回一个对象,
new
命令也会返回这个对象Reflect.construct
新的语法中,还有一个和
new
操作符行为相似的方法:Reflect.construct
区别在于,
Reflect.construct
允许使用可变参数来调用构造函数:上面的代码和 new 搭配展开运算符是等价的:
此外,
Reflect.construct
还可以替代 Object.create 来创建一个对象 Reflect.construct下一篇文章
面试题解JavaScript(三):call,apply 及 bind 函数的内部实现是什么样的
勘误与提问
如果有疑问或者发现错误,可以在相应的 issues 进行提问或勘误
如果喜欢或者有所启发,欢迎 star,对作者也是一种鼓励
(完)
The text was updated successfully, but these errors were encountered: