How come when I use the following code, clicking on “Click Here” doesn’t trigger an alert? Why can’t I call methods of things other than the window object? E.g. a method of the test1 function?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function test1() {
test1.test2 = function() {
alert('Test');
}
}
</script>
</head>
<body>
<div onClick="test1.test2()">Click Here</div>
</body>
</html>
Since you’re defining test1.test2 inside of test1, it won’t actually be defined until test1 executes.
Adding a call to test1() immediately after its definition in the script block would make your code work.
You could also move the definition of test1.test2 outside of test1, though if anything in test2 relies on variables which are scoped to test1 you’d have an issue.
All that said, you’re describing a weird scenario, code-wise.