1

This works ...

html file ...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="src/myJS.js"></script>
</head>
<body onload="myJS();">
</body>
</html>

Contents of external javascript file (called myJS.js for convenience) ...

myJS = function ()
{
    document.write("Hello world");
};

But, this does not work ...

html file ...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="src/myJS.js"></script>
</head>
<body onload="myJS.myFunction();">
</body>
</html>

external javascript file ...

myJS = function ()
{   
    myFunction = function()
    {
        document.write("Hello world");
    };  
};

Why not? Thanks in advance for any help.

2 Answers 2

3

A function declared inside another function does not become a property of that function. If you want myJS to be an object with myFunction as a method you can do this

myJS = {    
    myFunction: function()
    {
        document.write("Hello world");
    }   
};
Sign up to request clarification or add additional context in comments.

2 Comments

Would this be an example of closures?
@MartinJacobs No, just an object with a method.
0

your script creates two global functions...

so the myJS creates another function called myFunction either of which can be called independently.

looks like you want to make a JSON object like

myJS = {   
    myFunction: function() {
        document.write("Hello world");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.