Jump to content
iwato

A Matter of Scope

Recommended Posts

GENERAL QUESTION:  Can variables created outside of a function be used within a function without having to read them first as arguments of the function?  If so, can a function created within a function use a variable created outside of both functions?

CODE

		var dataString = 'search_input=' + search_letter_input;
		$.ajax({
			type: "POST",
			url: './...',
			data: dataString,
			dataType: 'JSON',
			statusCode: {
				404: function() {
				alert( "Page not found" );
			}},
			success: function(jsonData) {...}
		});

SPECIFIC QUESTION:  I would like to use the value of the variable search_letter_input in the success function of the $.ajax( ) method.  Is this possible?

Roddy

Share this post


Link to post
Share on other sites

I can't see where in your code it is declared, so I can't tell you if it is accessible. As long as the variable is declared outside of any other functions, it is accessible anywhere. Have you tried it?

  • Thanks 1

Share this post


Link to post
Share on other sites

No, i have not.  I thought I would check first, before I start writing.

The variable is declared earlier in the routine.  I will try it now.

Thank you!

Roddy

Share this post


Link to post
Share on other sites

Regardless of native JS or JQuery, perhaps this would help with your understanding:

	<script>
var globalVar = 'globalVar';
	function parentFunc() { // no function parameters
  var parentVar = 'parentVar';
	  function childFunc() { // not function parameters
    var childVar = 'childVar';
    alert('childFunc has access to:\n'+childVar+'\n'+parentVar+'\n'+globalVar);
  }
	  childFunc();
  alert('parentFunc has access to:\n'+parentVar+'\n'+globalVar);
}
alert('body has access to only:\n'+globalVar);
parentFunc();
</script>
	

 

  • Like 1
  • Thanks 1

Share this post


Link to post
Share on other sites

Thanks, JMRKER!

I have copied your script into my Javascript notes.  It will make it easy to remember, should I ever forget. :-)

Roddy

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...