简体   繁体   中英

Javascript: Uncaught TypeError: Cannot call method 'add' of undefined when referencing created object

First off i am not all that familiar with the OOP side of Javascript so i might need to go back to the drawing board and re-write the javascript as what i am trying to do may not be possible, so please let me know if that is so. I have been searching for a solution for this for a little while now but can't quite find the same issue in a way that i can understand what i should be changing.

I am using the class defined in this post: https://stackoverflow.com/a/7798773/1027442 .

When a combo box is changed (onChange) on the site it calls a Function which calls the function below to show a feedback box on the page:

var display_ajax_feedback = function (){

document.getElementById('ajax_feedback').style.display = 'block';

/*if(document.getElementById('ajax_feedback_active').value == "active"){*/
if(timer){
    timer.add(5000);
    }
else{
    var timer = new Timer(function() { // init timer with 5 seconds
            document.getElementById('ajax_feedback').style.display = 'none';
        }, 5000);

    /*document.getElementById('ajax_feedback_active').value ="active";*/
    }

}

The idea is that the "ajax_feedback" element displays for 5 sec then disappears, unless it is called again in which case 5 seconds is added.

When using this code the if(timer) line always returns false so the timer does not add on time but calls the object again.

I introduced the extra ajax_feedback_active element to force the timer.add method to be called but I get this error: " Uncaught TypeError: Cannot call method 'add' of undefined"

Is there anything that i am obviously doing wrong with this? And/or quick fix or am i going to have to re-think my approach to this?

If you need any further information please let me know.

Thanks in advance, Richard

Your timer is a variable in the function scope. Take the timer out from that function if you want to create a global reference to it, or get rid of that var keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM