In the <head> of my page, I do this:
<script type="text/javascript" src="js/foo.js"></script>
<script type="text/javascript">
console.log(foo.bar);
</script>
Code of foo.js:
var foo = function()
{
this.bar = function()
{
console.log('here');
}
}
Later on in the html document:
<a href="#" onclick="foo.bar();">Test</a>
However if I click that link above, it says function not defined even though foo.js has been included. Also if I do console.log(foo) it only shows ‘function()’ and console.log(foo.bar) shows undefined. Why is this, why can’t I access the function?
I’m not sure if you want it this way, but to get your
console.log(foo.bar);to work you can do this: