Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- JavaScript Question Response
- =-=-=-=-=-=-=-=-=-=-=-=-=-=
- Great question!
- If you are already familiar with the concept of scope then feel free to jump down to the *Hint* at the end of this explanation!
- ------
- Scope
- ------
- This problem touches upon a very important topic known as scope.
- When you write a program the variables you create are accessible based upon their scope.
- Consider the following example:
- function A(){
- var message = "This is from function A";
- alert(message);
- }
- function B(){
- var message;
- messsage = "This is from function B";
- alert(message);
- }
- function C(){
- var message = "This is from function C";
- function D(){
- alert(message);
- }
- D();
- }
- Let us first consider functions A and B:
- In both A and B we have a variable called message which exists within the scope of the function within which it was created.
- Notice in function B I have separated the declaration and the initialization of the variable called message.
- It is necessary for us to declare message in function B because the message we created in function A is no longer accesible once we leave A.
- If we were to write function B without the line "var message;",
- then message would be considered undefined,
- and our assignment into that variable during the following line,
- messsage = "This is from function B";
- would fail; we would get an error message in the console log when function B gets used
- (which you can check by right clicking on your browser and selecting the Inspect option).
- Now let's consider the curious case of function C:
- In function C we create another message, and we create another function called D.
- Inside D we don't need to declare message because D exists within the same scope as message,
- so calling D will alert with the value: "This is from function C".
- In terms of the problem you are experiencing:
- the variable btnNum is still alive in the scope that your onclick functions are;
- this means btnNum's value is right where you left it.
- The key to success for this problem will be determining how to create a new scope for each onclick function so that their btnNums live in separate scopes.
- ------
- *Hint*
- ------
- When you assign a function to a variable, you are assigning the actual text of that function.
- In order to send a function whose variables hold values it is important to initizalize the function.
- It is possible for a function to return another function.
- Happy coding!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement