Note that there are some explanatory texts on larger screens.

plurals
  1. POUncaught ReferenceError: X is not defined - declaring object on js file, making reference inside html button event
    text
    copied!<p>I want to define a Javascript object inside a js file and make it possible for users to create new instances of it on their HTML by calling the src on the head and then using "new". [maybe this is not the best approach, but bear with me] -- very basic stuff, right?</p> <p>Code in JS file myFile.js:</p> <pre><code>function myObject(){ this.myMethod = thisMethod; function thisMethod(){ return 2; } } </code></pre> <p>Code in HTML:</p> <pre><code>&lt;head&gt; &lt;script type="text/javascript" src="http://myserver/myFile.js"&gt; var customObject = new myObject(); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="Click Me" onclick="alert(customObject.myMethod());"&gt; &lt;/body&gt; </code></pre> <p>However, when you click the button, you get a "Uncaught ReferenceError: customObject is not defined" error.</p> <p>I am sure this is about how I am declaring the instance and then calling it. If I put the var declaration inside the js file, the click works:</p> <pre><code> function myObject(){ this.myMethod = thisMethod; function thisMethod(){ return 2; } } var customObject = new myObject(); </code></pre> <p>But this defeats the purpose of letting the user create the object and use it at will.</p> <p>Of course there is a problem with my structure, but all my researches don't give me a clue. I thought bringing the js file was the same as putting the code inside script tag in the HEAD and instantiating the object there -- because if I do that, without .js call, it works. </p> <p>I have many theories, some of them regarding events and the order where things are loaded, but don't want to clutter this question.</p> <p><strong>So the question is: how to you define an object in a js file, then let the user instantiate and call its methods inside the HTML? (Especially for events like onclick)</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload