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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×