为什么Bootstrap 4在es6类中使用私有方法

Why does Bootstrap 4 use private methods in es6 classes?

本文关键字:有方法 Bootstrap es6 为什么      更新时间:2023-09-26

我查看了Bootstrap 4的源代码,发现他们使用的是es6类,并结合了某种揭示模块模式

以下是从这里获得的代码的简化示例。

const Modal = (($) => {

  const NAME                         = 'modal'
  const VERSION                      = '4.0.0-alpha.3'
  ...
  const Default = {
    ...
  }

  class Modal {
    constructor(element, config) {
      this._config              = this._getConfig(config)
      this._element             = element
      ...
    }

    // public
    toggle(relatedTarget) {
      ...
    }
    show(relatedTarget) {
      ...
    }
    hide(event) {
      ...
    }
    dispose() {
      ...
    }

    // private
    _getConfig(config) {
      ...
    }
    _showElement(relatedTarget) {
      ...
    }
    _enforceFocus() {
      ...
    }
    _setEscapeEvent() {
      ...
    }
    _setResizeEvent() {
      ...
    }
  }
  return Modal
})(jQuery)
export default Modal

这将导致每个方法或属性都被公开,包括私有方法或属性。然而,这并不会发生在最终产品中。例如,像$('#myModal').modal('_getConfig')这样的东西是不起作用的。发生了什么?

它只向jQuery原型_jQueryInterface:添加了一个函数

  $.fn[NAME]             = Modal._jQueryInterface
  $.fn[NAME].Constructor = Modal
  $.fn[NAME].noConflict  = function () {
    $.fn[NAME] = JQUERY_NO_CONFLICT
    return Modal._jQueryInterface
  }
  return Modal
})(jQuery)

如果你查看_jQueryInterface的代码,你会看到:

static _jQueryInterface(config, relatedTarget) {
  return this.each(function () {
    let data    = $(this).data(DATA_KEY)
    let _config = $.extend(
      {},
      Modal.Default,
      $(this).data(),
      typeof config === 'object' && config
    )
    if (!data) {
      data = new Modal(this, _config)
      $(this).data(DATA_KEY, data)
    }
    if (typeof config === 'string') {
      if (data[config] === undefined) {
        throw new Error(`No method named "${config}"`)
      }
      data[config](relatedTarget)
    } else if (_config.show) {
      data.show(relatedTarget)
    }
  })
}

如果我们仔细观察,您会发现类Modal的实例被保存为data:

    if (!data) {
      data = new Modal(this, _config)
      $(this).data(DATA_KEY, data)
    }

您可以以与脚本相同的方式访问它(但只有在第一次创建它之后):

let data    = $(this).data(DATA_KEY)

DATA_KEYbs.modal

编辑:

$('#myModal').modal('_getConfig');

函数_getConfig实际上正在被调用,只是该函数正在返回jQuery对象,而不是_getConfig的结果