Reputation: 1944
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?
Code in JS file myFile.js:
function myObject(){
this.myMethod = thisMethod;
function thisMethod(){
return 2;
}
}
Code in HTML:
<head>
<script type="text/javascript" src="http://myserver/myFile.js">
var customObject = new myObject();
</script>
</head>
<body>
<input type="button" value="Click Me" onclick="alert(customObject.myMethod());">
</body>
However, when you click the button, you get an error:
"Uncaught ReferenceError: customObject is not defined"
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:
function myObject(){
this.myMethod = thisMethod;
function thisMethod(){
return 2;
}
}
var customObject = new myObject();
But this defeats the purpose of letting the user create the object and use it at will.
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.
I have many theories, some of them regarding events and the order where things are loaded, but don't want to clutter this question.
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)
Upvotes: 1
Views: 4699
Reputation: 6322
The problem is that you can't use the same tag to both include an external resource and define your javascript code. You have to use 2 separate tags, otherwise whatever code you put inside the tags will be omitted. This works fine:
<script type="text/javascript" src="http://myserver/myFile.js"></script>
<script type="text/javascript">
var customObject = new myObject();
</script>
Hope it helps,
Upvotes: 2