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
步骤 3 中,将新创建的对象作为了当前函数 this 的上下文,这也是为什么通过 new 创建实例时,构造函数内部的 this 指向创建的实例对象的原因。
手写
functionobjectFactory(){varobj=newObject(),//从Object.prototype上克隆一个对象Constructor=[].shift.call(arguments);//取得外部传入的构造器varF=function(){};F.prototype=Constructor.prototype;obj=newF();//指向正确的原型varresult=Constructor.apply(obj,arguments);//借用外部传入的构造器给obj设置属性returntypeofresult==='object' ? ret : obj;//确保构造器总是返回一个对象};
new
是一个运算符new
的作用,就是执行构造函数,返回一个实例对象new
的功能:Function
构造函数里的函数Function.prototype
中的属性new
做了什么:实现原理
使用
new
命令时,它后面的构造函数会执行以下操作:prototype
属性this
绑定到空对象this
,即新创建的对象步骤 3 中,将新创建的对象作为了当前函数
this
的上下文,这也是为什么通过new
创建实例时,构造函数内部的this
指向创建的实例对象的原因。手写
new Object()
的方式新建了一个对象 objarguments
会被去除第一个参数apply
,改变构造函数this
的指向到新建的对象,这样 obj 就可以访问到构造函数中的属性https://mp.weixin.qq.com/s?__biz=MzAxODE2MjM1MA==&mid=2651555993&idx=1&sn=37bb41a7e178083de174bfd51308d369&chksm=80255f58b752d64e3006feb7d14b1e0cf47414f98863dc0ffb46b524f2926ac0dea805210353&mpshare=1&scene=1&srcid=%23rd
campcc/blog#3
https://juejin.im/post/5bde7c926fb9a049f66b8b52
The text was updated successfully, but these errors were encountered: