用大白话🙌带你掌握闭包

475 阅读1分钟

image.png

最近看了一些关于闭包的文章,到后面真正理解闭包时,发现其实大多数文章讲得还是稍微复杂了一点。

其实一开始我以为闭包是个很高大上,很高深莫测的知识点,但其实并不是的,如果光看那描述的很官方的定义以及巨长的闭包文章滚动条的话,一开始确实会被劝退😰。接下来我会尽量简易地结合例子去描述这个知识点,OK,开始吧! 你好创作中心

[ function analog_new(constructor, ...rest) {
    if (typeof constructor !== 'function') {
        return constructor;
    }
    //创建新的对象,关联构造函数的原型对象
    const _constructor = Object.create(constructor.prototype);
    //执行构造函数
    const obj = constructor.apply(_constructor, rest);
    //如果构造函数执行结果是对象则返回执行结果
    if (typeof obj === 'object') {
        return obj;
    } else {
        return _constructor;
    }
 };](url)