search

Home  >  Q&A  >  body text

javascript - export method reports an error of undefined after exporting

Because jquery was not integrated at the beginning of the project, many methods were written natively. Today I went online to find several methods for manipulating class names, as follows:

export const hasClass = (el, cls) => {
    return el.className.match(new RegExp('(\s|^)' + cls + '(\s|$)'))
}

export const removeClass = function (el, cls) {
    if (hasClass(el, cls)) {  
        var reg = new RegExp('(\s|^)' + cls + '(\s|$)')
        el.className = el.className.replace(reg, ' ')
    }  
}

export const addClass = function (el, cls) {
    if (!this.hasClass(el, cls)) el.className += " " + cls
}

export const toggleClass = (el,cls) => {
    console.log(hasClass)
    if(hasClass(el,cls)){
        removeClass(el, cls)
    }else{
        addClass(el, cls)
    }  
}

But when I use it, I always get an error, as follows:

Uncaught TypeError: Cannot read property 'hasClass' of undefined
    at addClass (Route.js?7c64bfe…:27892)
    at HTMLpElement.item.onclick (Route.js?7c64bfe…:139726)

I interrupted and debugged, but still couldn't find the cause of the problem. I wonder if any of you have encountered the same problem?

高洛峰高洛峰2714 days ago1017

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-06-26 10:59:31

    export const addClass = function (el, cls) {
        if (!this.hasClass(el, cls)) el.className += " " + cls
    }
    
    就是this的问题。直接把this.去掉,固定调用模块内部的hasClass方法。
    export const toggleClass = (el,cls) => {
        console.log(hasClass)
        if(hasClass(el,cls)){
            removeClass(el, cls)
        }else{
            addClass(el, cls)
        }  
    }

    It is correct to call addClass and removeClass in toggleClass. Why do you remember adding this in front of hasClass?

    reply
    0
  • 習慣沉默

    習慣沉默2017-06-26 10:59:31

    It depends on what object this refers to in your this.hasClass(). You can check whether this refers to the global object

    reply
    0
  • Cancelreply