Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

代码使用了Function.prototype.call()知识点,我哪里理解错了?

MDN定义:**call()**?方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

let dom = {
    on: function(element, eventType, selector, fn) {
    element.addEventListener(eventType, e => {
      let el = e.target
      while (!el.matches(selector)) {
        if (element === el) {
          el = null
          break
        }
        el = el.parentNode
      }
      el && fn.call(el, e, el)  // 这里的call方法第一个参数不是相当传了个this对象吗???
    })
    return element
  },

}
class Tabs {
  constructor(options) {
    let defaultOptions = {
      element: '',
      navSelector: '[data-role="tabs-nav"]',
      panesSelector: '[data-role="tabs-panes"]',
      activeClassName: 'active',
    }
    this.options = Object.assign({}, defaultOptions, options)
    this.checkOptions().bindEvents().setDefaultTab()
  }
  checkOptions() {
    if (!this.options.element) {
      throw new Error('element is required')
    }
    return this
  }
  bindEvents() {
    dom.on(this.options.element, 'click', `${this.options.navSelector}>li`, (e, el) => {
      console.log(this === el)  // 为啥这里输出false???
      let index = dom.index(el)
      let children = this.options.element.querySelector(this.options.panesSelector).children
      dom.uniqueClass(el, this.options.activeClassName)  //处理[data-role="tabs-nav"]的activeClassName
      dom.uniqueClass(children[index], this.options.activeClassName) //处理[data-role="tabs-panes"]的activeClassName
    })
    return this
  }
  setDefaultTab() {
    this.options.element.querySelector(`${this.options.navSelector}>li:first-child`).click()
    return this
  }
}

在bindEvents方法里输出this===el 结果为啥是false?执行 fn.call(el, e, el)不是把el作为this传进去了吗?该如何理解call方法第一参数的意义?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

学习下 箭头函数 的知识点


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...