javascript - export method reports an error of undefined after exporting
高洛峰
高洛峰 2017-06-26 10:57:31
0
2
1014

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?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
ringa_lee
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?

習慣沉默

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template