zjmiller
zjmiller

Reputation: 2807

Conceptual question about functions within functions

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>

Upvotes: 1

Views: 174

Answers (4)

JAAulde
JAAulde

Reputation: 19560

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.

Upvotes: 3

adt
adt

Reputation: 4360

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function test1(){

test1.prototype.test2 = function(){
alert('Test');
}

}


</script>
</head>
<body>

<div onClick=" var u = new test1();u.test2()">Click Here</div>
</body>
</html>

Upvotes: 0

Steven D. Majewski
Steven D. Majewski

Reputation: 2167

test1.test2 is undefined until test1() has been called.

~$ rhino
Rhino 1.7 release 2 2009 03 22
js> function test1() { 
  > test1.test2 = function() { print( 'Test\n' ); } 
  > }
js> test1

function test1() {
    test1.test2 = function () {
        print("Test\n");
    };
}

js> test1.test2   # Undefined!
js> test1()
js> test1.test2

function () {
    print("Test\n");
}

js> test1.test2()
Test

Upvotes: 3

Hamish
Hamish

Reputation: 23346

test1 is a function, not an object.

For example, the following would work:

<script type="text/javascript">
test1 = {
    test2 : function(){
        alert('Test');
    }
}
</script>
<div onClick="test1.test2()">Click Here</div>

Or

<script type="text/javascript">
function test1() {
    this.test2 = function(){
        alert('Test');
    }
}
var t1 = new test1();
</script>
<div onClick="t1.test2()">Click Here</div>

Upvotes: 0

Related Questions