模拟实现JS的new操作符、继承和ES6中class的实现原理

一、使用 new 操作符调用构造函数实际上会经历以下 4个步骤:

(1) 创建一个新对象;
(2) 将构造函数的作用域赋给新对象(因此 this 就指向了这个新对象) ;
(3) 执行构造函数中的代码(为这个新对象添加属性) ;
(4) 返回新对象,如果该函数没有返回对象,则返回this。

function myNew(fn, ...arg) {
    if (typeof fn !== 'function') {
        throw new Error('myNew the first params must be a function')
    }
    // 
    let obj = Object.create(null)
    // 将空对象指向构造函数的原型链
    Object.setPrototypeOf(obj, Con.prototype);
    let res = fn.call(obj, ...args)

    return typeof res === 'object' || res instanceof Function ? res : obj;
}

二、原型链、constructor继承

'use strict'
        const inherit = function (SuperConstructor, properties) {
            let { constructor } = properties
            let subConstructor = function(...args){
                constructor.call(this, ...args)
                SuperConstructor.call(this, ...args)
            }
            subConstructor.prototype = {
                ...properties,
                constructor: subConstructor
            }
            Object.setPrototypeOf(
                subConstructor.prototype,
                SuperConstructor.prototype,
            )
            return subConstructor
        }
        const Human = inherit(Object, {
            constructor( age ) {
                this.age = age
            },
            showAge() {
                console.log(this.age)
                return this.age
            }
        })
        const User = inherit(Human, {
            constructor({ firstname, lastname }) {
                this.firstname = firstname
                this.lastname = lastname
            },
            showName() {
                console.log('name', this.firstname + '' + this.lastname)
            }
        })
        const user = new User({
            age: 18,
            firstname: 'Jade',
            lastname: 'Gu'
        })
        console.log('User', User)

三、ES6中class的实现原理

ES6类以及继承的实现原理_当年明月又天涯的博客-CSDN博客_es6继承的原理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值