Why this simple code does not work?


#1

why this simple code does not work?


#2

It doesn’t work because you didn’t define test1(). The line test1() is not simple. It is to be working if there is some definition of it.


#3

I don’t understand. ‘test1()’ function is defined immediately after the ‘test()’ function.
But it is doesn’t work


#4

Test 1 needs to be defined before test() runs. (aka test() needs to be put after test1())


#5

You didn’t run the function, either.


#6

actually I ran the function at line 1


#7

@Seojin_Roy_Lee test1() is called upon within test()


#8

Oh. (I hate 20 char)


#9

In the code below function ‘test1()’ is still after the function ‘test()’, but code works fine.
Just function ‘test()’ is called after all definitions.

function test()
{
	test1();
}
function test1()
{
	hero.say('ok');
}
test();

I don’t understand, why?
Is it a game bug or feature?


#10

switch the order of the functions.


#11

You have to define a function before you can call it.

It works in the second format because you call on test() after defining it. In the first version you tried to call a function that doesn’t exist yet because you hadn’t defined it yet.


#12

Not correct, because the following code works, although the function is defined after the call

test();

function test() {
    hero.say("It works");
}

#14

You’re right, but I prefer another style of programming. When the function declarations are at the bottom.
I’m not asking how to write code, I’m indicate to a bug in the game.


#15

It’s not a bug. You should search online for why this happens (I’m sure there’s an explanation)


#16

I’m sorry, but it’s a bug.
2 Facts:

  1. In the error message says that some variable “v” is undefined. But the code does not have the variable “v”.
  2. The following code works in any modern browser (and even in IE8):
<!-- Test.html-->
<script>

	test();
	
	function test()
	{
		test1();
	}
	
	function test1()
	{
		alert('ok');
	}
</script>

#18

Hey Gaulina,

You’re absolutely right that it’s a bug. Esper only does var hoisting mechanics for functions, which covers the use-case of functions referring to functions defined below them. However the function isn’t actually defined until execution reaches it’s declaration.

I’ll work on getting that fixed up. :slight_smile: