第十八篇 如何模拟实现一个new的效果?
new 被调用后做了三件事情:
- 让实例可以访问到私有属性
- 让实例可以访问构造函数原型(constructor.prototype)所在原型链上的属性
- 如果构造函数返回的结果不是引用数据类型
function newOperator(ctor, ...args) { if(typeof ctor !== 'function'){ throw 'newOperator function the first param must be a function'; } let obj = Object.create(ctor.prototype); let res = ctor.apply(obj, args); let isObject = typeof res === 'object' && res !== null; let isFunction = typoof res === 'function'; return isObect || isFunction ? res : obj; };
更多相关文章推荐:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 第十八篇 如何模拟实现一个new的效果?
码云笔记 » 第十八篇 如何模拟实现一个new的效果?