I am trying to call a method in a javascript class when a button is clicked. My test program is below. I've tried a number of things based on what I've found on the internet, but I can't get it to work. I would appreciate any help you can give me. Thanks.

<!DOCTYPE html> <html> <head> <title>Test</title> </head> <body> <script>
            function Circuit(){         // class Circuit
                function run(){         // method run
                    alert("running");
                };
            }

            var circuit = new Circuit();

            function runCircuit(){
                circuit.run();
            }

        </script> <input type="button" onclick="runCircuit();" value="Click"/> </body> </html> 

Think it over. Line 8 is in the script so it may have never run. Try line 8 after line 10.

Sorry about that. My mistake. That change would only change the scope.

First , - use any browser built in tool (like Chrome developer tools) or a plug in. If you had done it you would have get “Uncaught TypeError: circuit.run is not a function” (I run it myself to be correct about the error (I was thinking that the error message would be even more enlightening) ).

When in the Circuit function class (lets call it class) you declare run as function it means that it can be accessed only within that class. It is like it was private. If you want to expose it through an instance of that function class (a function object) (public) you should declare it as:

               this.run = function()
               {        
                    alert("running");
               };
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.