Skip to content Skip to sidebar Skip to footer

Two Same Name Variables

In https://github.com/Khan/khan-exercises/blob/master/khan-exercise.js there are two var Khan variables. How come? Do they affect each other?

Solution 1:

One Khan is the name of the global variable "Khan", the other is a variable inside the self executing function that it is equal to.

varKhan = (function(){

    ....

    varKhan = ...

    ....

})();

The indentation in the source file is horrible and you probably did not notice that....

Solution 2:

variables wrapped in anonymous functions only work inside that function.

So this should work okay.

<scripttype="text/javascript">
$(function(){
   var khan = (function(){
        var khan = //this should not be a problem and they both work, this will be only available in the function
   }); 
});
</script>

Post a Comment for "Two Same Name Variables"